在下面的例子中,我不明白爲什麼Base b1 = new Derived(); System.out.println(b1);
打印出x=10, z=20
。我的理解是,因爲b1
有一個靜態類型的基地,它不能訪問Derived
中的字段,所以z
不應該打印出來。有人可以幫忙解釋嗎?非常感謝!Java更寬的對象分配轉換
class Base {
int x;
public Base1() { x = 10; }
public Base1(int x) { this.x =x; }
public String toString() {
return "x=" + x ;
}
}
class Derived1 extends Base1 {
int z = x * 2;
public Derived1() {}
public Derived1(int x, int z) {
super(x);
this.z = this.z + z;
}
public String toString() {
return "x=" + x + ", z=" + z;
}
}
這是多態性的全部目的。 – 2014-09-13 09:20:08
https://en.wikipedia.org/wiki/Method_overriding – khelwood 2014-09-13 09:34:27