简体   繁体   English

当我们使用多态性时,Memory 是如何工作的?

[英]How does the Memory work when we use Polymorphism?

There is kind of a similar blog but I'm interested from kind of a different view.有一种类似的博客,但我从不同的角度感兴趣。

Consider these two classes考虑这两个类

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;
    }
}

In the main method在主要方法中

        Parent obj = new Child(1, 2);
        Child childObj = (Child) obj;
        System.out.println(childObj.x + " " + childObj.y);

If we look at this we can get our x and y back even though we started everything with Parent which can't store y at all (It has only x field as you can see).如果我们看一下,即使我们从根本无法存储yParent开始一切(如您所见,它只有x字段),我们也可以取回我们的xy

When we create a Child object with Parent where does the extra variable y go (since the Parent can only store variable x )?当我们用Parent创建一个Child object 时,额外的变量y go 在哪里(因为Parent只能存储变量x )?

From my little knowledge there is a Parent in the stack referencing the Child in the heap, which saves x , y and the class from which the new was called.据我所知,堆栈中有一个Parent引用了堆中的Child ,它保存了xy和调用new的 class 。

Can you verify, deny, extend my idea?你能验证、否认、扩展我的想法吗?

Java offers polymorphism only for reference types. Java 只为引用类型提供多态性。 That is, a variable of type Parent merely contains a reference to an object located elsewhere.也就是说, Parent类型的变量仅包含对位于其他位置的 object 的引用。 The same reference can refer to different objects over time, and these may be of different subtypes and sizes.随着时间的推移,同一个引用可以引用不同的对象,这些对象可能具有不同的子类型和大小。

That is, when you do Parent obj = new Child(1,2) a single object of type Child is created, which stores the fields it inherits from its supertypes ( x ) in addition to the fields it declared itself ( y ).也就是说,当您执行Parent obj = new Child(1,2)时,会创建一个Child类型的 object,除了它声明的字段 ( y ) 之外,它还存储从其超类型 ( x ) 继承的字段。

When later accessing parent.x , the JVM reads the reference, and finds the corresponding object, and then proceeds to read its x .稍后访问parent.x时,JVM 读取引用,并找到对应的 object,然后继续读取其x To simplify this process, most VMs keep the x field in the same place for all subtypes of Parent , so the VM can read the field the same way irrespective of the object's actual type.为了简化此过程,大多数 VM 将x字段针对Parent的所有子类型保留在同一位置,因此 VM 可以以相同的方式读取该字段,而与对象的实际类型无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM