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