简体   繁体   中英

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).

When we create a Child object with Parent where does the extra variable y go (since the Parent can only store variable 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.

Can you verify, deny, extend my idea?

Java offers polymorphism only for reference types. That is, a variable of type Parent merely contains a reference to an object located elsewhere. 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 ).

When later accessing parent.x , the JVM reads the reference, and finds the corresponding object, and then proceeds to read its 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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