Java Puzzler - 任何人都可以解释这种行为吗?
问题描述:
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();
}
}
上述程序产生以下输出:Java Puzzler - 任何人都可以解释这种行为吗?
Value in Derived1: 0
Value in Derived1: 10
我没有得到为什么print()
在AbstractBase
构造函数总是被为什么不映射到最派生的类(这里Derived1
)print()
DerivedClass
的print()
?有人能帮助我理解这一点吗?
这是一个不错的谜题,但不要在生产代码中这样做。 – starblue 2009-10-03 15:39:33