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构造函数总是被为什么不映射到最派生的类(这里Derived1print()

DerivedClassprint()?有人能帮助我理解这一点吗?

+0

这是一个不错的谜题,但不要在生产代码中这样做。 – starblue 2009-10-03 15:39:33

因为并非明确地调用super调用的所有Java方法调用都会派发到派生类最多的类,即使在超类构造函数中也是如此。这意味着超类可以获得子类行为的好处,但这也意味着重写方法在理论上可以在该类的构造函数之前被调用。

+0

约翰你有明确解释这种行为的一些参考(在Java规范等某处) – peakit 2009-10-03 08:22:58

+1

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.4 – starblue 2009-10-03 15:38:45

Super Class构造函数中的虚拟化。

看看Virtualization in Super Class Constructor