【发布时间】:2014-09-13 09:18:58
【问题描述】:
在下面的例子中,我不明白为什么Base b1 = new Derived();
System.out.println(b1); 会打印出x=10, z=20。我的理解是,由于b1 有一个静态类型的Base,它无权访问Derived 中的字段,所以z 不应该被打印出来。有人可以帮忙解释一下吗?非常感谢!
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;
}
}
【问题讨论】:
-
这就是多态性的全部目的。
标签: java casting reference field typing