1

为什么第一个 System.out.println 不打印值 10?它打印一个 0。首先创建一个新的子对象,它调用父对象中的构造函数。由于动态绑定,Parent 中的构造函数调用 Child 中的查找。那么为什么在 Child 中查找返回零而不是十呢?

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
    } 
}
4

1 回答 1

3

in的字段初始值设定项num在构造函数调用 in之后Child执行。因此返回 0,因此设置为 0。Parentlookup()Parent.val

要观察这一点,请更改Child.lookup()以打印出它即将返回的内容。

有关创建新实例时的执行顺序的详细信息,请参阅Java 语言规范的第 12.5 节。

于 2013-02-15T14:00:53.310 回答