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()
inAbstractBase
构造函数总是被映射到最派生的类(这里Derived1
)print()
为什么不去DerivedClass
的print()
?有人可以帮助我理解这一点吗?