Reputation: 61
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"?
Upvotes: 6
Views: 99
Reputation: 72844
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.
Upvotes: 1
Reputation: 41271
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.
Upvotes: 1