强制转换Java对象分配转换
在下面的例子中,我不明白为什么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;
}
}
# 1 楼答案
直接从http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
在代码中,您调用默认构造函数来创建一个新的
Derived1
对象:Base b1 = new Derived();
,这反过来又调用您碰巧设置x = 10
的父类的默认构造函数。在那之后,你进入这一行int z = x * 2;
# 2 楼答案
对象是
Derived
,而不是Base
。从b1
到对象的接口是Base
Base
有toString
,所以你可以访问toString
。您访问的实现是对象拥有的实现,它由使用Derived
的z
提供。Derived#toString
的实现可以访问z
,因为它对对象的引用是通过Derived
引用(this
)而不是Base
引用进行的正如奥利在一篇评论中指出的,这是多态性的基础——让对象的行为取决于对象,而不是对象的接口
如果对象的内部是由我们与它的接口决定的,那么我们在实现
interface
s!时会遇到相当大的麻烦:-)