简体   繁体   中英

JVM Memory Allocation

Hi I Have a question about inheritance. In Java, a subclass object have inside it an object of its superclass?

When JVM allocate space for subclass object, allocates space for superclass field/method? Thanks.

Example:

class Bar {
    public String field;

    public Bar() {
        this.field = "Bar";
    }
}

class Foo extends Bar {
    public String field;

    public Foo() {
        this.field = "Foo";
    }

    public void printFields() {
        System.out.println("Base: " + super.field);
        System.out.println("This: " + this.field);
    }
}

In execution, will print "Bar" and "Foo". Where Java allocate space to mantain both value for "field"?

Yes, Java will allocate space for two object references--one for Foo.field and the other for Bar.field . Loosely speaking, this can be a way to visualize an instance of Foo in memory:

[header] (references Foo.class, Bar.class, Object.class, among other details)
[Section for Bar]:
    Field, declared type String, referencing a `java.lang.String` with value "Bar"
[Section for Foo]:
    Field, declared type String, referencing a `java.lang.String` with value "Foo"

The offsets of these fields are known to the JVM and are used when reading/writing them.

Note that this does not imply Foo contains a Bar , but rather Foo is a Bar and more.

In Java, a subclass object have inside it an object of its superclass.

No. A subclass does not "contain" its parent object. Inheritance is an "is-a" relationship. An instance of Foo is an instance of Bar . Not that Foo contains Bar .

When JVM allocate space for subclass object, allocates space for superclass field/method?

Yes. Although the subclass Foo has a field with the same name (hence "shadowing" the parent's field), there are still two fields allocated in memory.

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