我有以下示例代码解释示例多态性概念 - 覆盖
class Super { public int number = 1; public char superText='a'; public String getColor() { return "red"; } } class Sub extends Super { public int number = 2; public char subText='b'; public String getColor() { return "blue"; } } public class Sample2 { public static void main(String[] args) { Super supersub = new Sub(); System.out.println( supersub.getColor() + supersub.number + supersub.superText ); } }
输出是 blue1。
问题 1:
重写派生类getColor()方法,显示Super类的Field。
有人可以解释为什么不调用派生类中的数字字段吗?即,输出为 blue2
问题 2: *关于内存分配*
对于下面的对象实例化,
Sub subobj = new Sub();字段“number”的内存在堆中分配,Number 变量的地址 分配给对象引用,子对象。
考虑以下情况,
Super supersub = new Sub();
(a) 这里创建派生类“Sub”中的变量、“number 和 subText”的内存,并将变量的地址放在 supersub 对象中
当我访问 supersub.subText 时出现无法解析 subText 的错误。
所以,请解释上面描述的 要点 (a),即派生类变量的内存分配
谢谢, 半机械人
最佳答案
Question 1:
The Method is derived class is displayed and Field of the Super class is displayed.
Can some one explain why number field in derived class is not called ? i.e., output is blue2
字段不能被覆盖。即使两个类共享父子关系,字段也属于定义它们的类,即使它们与继承的字段共享名称。换句话说,Sub
中的number
与Super
中的number
是完全不同的字段。
Question 2: Here memory for variables, 'number and subText' in derived class 'Sub' is created and the address of the variables is placed in supersub Object when i access, supersub.subText i got error that subText cannot be resolved.
supersub
中存储的对象是Sub
类型,但编译器不知道。
因为 Java 是一种静态类型语言,所以编译器会根据引用的声明类型(即变量类型)进行处理,因为在大多数现实世界中在某些情况下,运行时 类型(new
表达式中明显的类型)在编译时不一定已知。例如,您可能从另一个方法或两个或三个候选方法中获取了此对象,因此运行时类型是不可预测的。
将引用存储在父类(super class)变量中意味着您打算将该对象用作 Super
一段时间。然后,编译器根据您的这种感知意图进行工作。 Super
不能保证只有 Sub
运行时类型的实例,因此它不能做出您期望的假设。
也就是说,将引用存储在一种或另一种变量中不会修改对象。如果您要将该对象转换回一个变量,该变量的类型实际上知道您要访问的那些成员(在您的例子中是 Sub
类型),您会发现它们'他们仍然在那里(并且他们保留了他们的值(value)观)。
关于java - Java 多态中对象的字段访问和内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14834873/