Test3.java:
public class Test3 {
public static void main(String[] args) {
A a = new A();
}
}
class A extends B {
A() {
System.out.println("Now in A()");
}
void m() {
System.out.println("Now in m() of A");
}
}
class B {
B() {
System.out.println("Now in B()");
m();
}
void m() {
System.out.println("Now in m() of B");
}
}
输出:
$ java Test3
Now in B()
Now in m() of A
Now in A()
为什么不在第二行输出“Now in m() of B”?
最佳答案
因为 m
方法在 A
中被覆盖了。所以当它转到 super 构造函数,并调用m
时,该对象仍然是A
的一个实例,所以它调用了A
中的方法.
关于java - 为什么父类(super class) B 调用子类 A 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25588310/