2013-02-15 66 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

相关问题