pea*_*kit 2 java puzzle abstract-class
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();
}
}
Run Code Online (Sandbox Code Playgroud)
上面的程序产生以下输出:
Value in Derived1: 0
Value in Derived1: 10
Run Code Online (Sandbox Code Playgroud)
我不明白为什么print()in AbstractBase构造函数总是被映射到派生程度最高的类(这里Derived1)print()
为什么不来DerivedClass的print()?有人能帮助我理解这个吗?
因为所有非显式super调用的Java方法调用都被调度到最派生类,即使在超类构造函数中也是如此.这意味着超类可以获得子类行为的好处,但这也意味着理论上可以在该类中的构造函数之前调用重写方法.
| 归档时间: |
|
| 查看次数: |
263 次 |
| 最近记录: |