JVM memory allocation

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

When does the JVM allocate space for a subclass object, allocates space for a 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); } } 

During the execution, "Bar" and "Foo" will be printed. Where does Java allocate space for storing both values ​​for the "field"?

+6
source share
2 answers

Yes, Java will allocate space for two object references - one for Foo.field and one for Bar.field . In short, this could be a way to render 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.

Please note that this does not mean that Foo contains a Bar , but rather Foo is a Bar and more.

+1
source

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

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

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

Yes. Although the Foo subclass has a field with the same name (hence the β€œshading” of the parent field), there are still two fields in memory.

+1
source

Source: https://habr.com/ru/post/990051/


All Articles