Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JVM Memory Allocation

Tags:

java

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"?

like image 669
JCoder Avatar asked Jun 30 '15 20:06

JCoder


2 Answers

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.

like image 86
nanofarad Avatar answered Oct 02 '22 03:10

nanofarad


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.

like image 33
M A Avatar answered Oct 02 '22 04:10

M A