第一个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
}
}
当我将Child中的num改为静态时,该如何得到值10? – 2013-02-15 15:23:56