【Java基础】通过子类调用父类被重写的方法

238 阅读1分钟

多态

使用super关键字可以通过子类调用父类被重写方法。

public class Main {
    public static void main(String[] args) {
        Children c = new Children();
        c.method();
    }
}

class Father {
    public void method() {
        System.out.println("I'm father.");
    }
}

class Children extends Father {
    @Override
    public void method() {
        System.out.println("I'm children.");
        super.method();
    }
}

输出

I'm children.
I'm father.

或者这样

public class Main {
    public static void main(String[] args) {
        Children c = new Children();
        c.method();
    }
}

class Father {
    String name;
    public void method() {
        name = "father";
        System.out.println(name);
    }
}

class Children extends Father {
    String name;
    @Override
    public void method() {
        name = "children";
        super.method();  // 打印father
        System.out.println(name);  // 打印children
    }
}


输出

father
children