【发布时间】:2021-07-22 18:50:12
【问题描述】:
有一个类似的博客,但我从不同的角度感兴趣。
考虑这两个类
public class Parent {
int x;
public Parent(int x) {
this.x = x;
}
}
public class Child extends Parent {
int y;
public Child(int x, int y) {
super(x);
this.y = y;
}
}
在main方法中
Parent obj = new Child(1, 2);
Child childObj = (Child) obj;
System.out.println(childObj.x + " " + childObj.y);
如果我们查看这个,我们可以找回我们的 x 和 y,即使我们以 Parent 开始所有内容,它根本无法存储 y(它只有 x 字段,因为你可以见)。
当我们用Parent 创建一个Child 对象时,额外的变量y 去哪里(因为Parent 只能存储变量x)?
据我所知,堆栈中有一个Parent 引用堆中的Child,它保存了x、y 和调用new 的类。
你能验证、否认、扩展我的想法吗?
【问题讨论】:
-
到目前为止,您的假设是正确的:只有堆栈上的引用具有 Parent 类型,这意味着它可以指向内存中满足该 Parent 类型的接口/合同的所有对象。它并不真正关心堆中 Child 对象的其他字段。
-
Parent obj = new Child(1, 2);- 很快:被视为Parent,但实际上是Child。
标签: java oop inheritance memory polymorphism