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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With