2013-02-15 57 views
1

第一個System.out.println如何不打印10的值?它打印一個0.首先創建一個新的Child對象,它調用Parent中的構造函數。由於動態綁定,Parent中的構造函數在Child中調用查找。那麼爲什麼在Child中查找返回一個零而不是十?傳統,動態綁定,超類中的構造函數。 Java

public class Main332 { 
    public static void main(String args[]) { 

     Child child = new Child(); 
     System.out.println("child.value() returns " + child.value());//Prints 0 

     Parent parent = new Child(); 
     System.out.println("parent.value() returns " + parent.value());//Prints 0 

     Parent parent2 = new Parent(); 
     System.out.println("parent2.value() returns " + parent2.value());//Prints 5 
    } 
} 


public class Child extends Parent { 
    private int num = 10; 

    public int lookup() { 
     return num; 
    } 
} 


public class Parent { 
    private int val; 

    public Parent() { 
     val = lookup(); 
    } 

    public int value() { 
     return val; 
    } 

    public int lookup() { 
     return 5;// Silly 
    } 
} 
+0

當我將Child中的num改爲靜態時,該如何得到值10? – 2013-02-15 15:23:56

回答

3

Child場初始化爲num是在Parent構造函數調用後執行。因此lookup()返回0,因此Parent.val設置爲0.

要觀察此操作,請更改Child.lookup()以打印出要返回的內容。

有關創建新實例時執行順序的詳細信息,請參閱section 12.5 of the Java Language Specification

+0

+1鏈接到jls – oliholz 2013-02-15 14:04:40

相關問題