abstract class AbstractBase {
abstract void print();
AbstractBase() {
// Note that this call will get mapped to the most derived class's method
print();
}
}
class DerivedClass extends AbstractBase {
int value = 1;
@Override
void print() {
System.out.println("Value in DerivedClass: " + value);
}
}
class Derived1 extends DerivedClass {
int value = 10;
@Override
void print() {
System.out.println("Value in Derived1: " + value);
}
}
public class ConstructorCallingAbstract {
public static void main(String[] args) {
Derived1 derived1 = new Derived1();
derived1.print();
}
}
上述程序产生以下输出:
Value in Derived1: 0
Value in Derived1: 10
我无法理解为什么print()
构造函数中的AbstractBase
始终会映射到派生程度最高的类(此处Derived1
)print()
为什么不到DerivedClass
的{{1}}?有人可以帮助我理解这个吗?
答案 0 :(得分:9)
因为所有非显式super
调用的Java方法调用都被调度到最派生类,即使在超类构造函数中也是如此。这意味着超类可以获得子类行为的好处,但这也意味着理论上可以在该类中的构造函数之前调用重写方法。
答案 1 :(得分:2)
超类构造函数中的虚拟化。