2009-10-03 122 views
2
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

回答

9

因爲並非明確地調用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

相關問題