第一個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