Reputation: 163
In multiple explanations, it is explained that only one object is created during inheritance. However, during inheritance from a superclass, a subclass does not inherit its parent's private attributes.
However, when a subclass calls its parents non-static getter method, it clearly is taking the value from some parent object, not a class. Then it seems that when you create a subclass object, a superclass object is also created that stores those private attributes.
Then are there essentially two copies of inherited methods and attributes? For example, if a superclass object A has a subclass object B. Then inside B there is both a super.attribute and a this.attribute because a hidden A object is also created? How then do constructors know the difference between attributes? For example, A has a constructor that sets a public attribute to 4. B then calls that constructor and sets the same attribute to 5. But B inherits that attribute as well, no? So does it get reset to 4? Or does the super.attribute = 4 and this.attribute = 5? Thus an attributes' value isn't inherited, but its existence is?
Upvotes: 2
Views: 114
Reputation: 352
Java always creates only one object when you create a new instance of any class, regardless of how many other classes it extends.
When the object is being instantiated, it contains all of the public and private fields but they are all available only in their specific scope.
If you need to know more about how the object is being stored in memory, here's an example:
class A {
private boolean attribute;
}
class B extends A {
private boolean attribute;
}
B inst = new B();
In this case, inst
will be a single object which contains both private fields - one can be accessed only inside A, the other - only inside B. JVM does not store fields by their names - fields are just a section of memory and JVM handles them separately.
If you want to know more about the inner representation of your class, I highly suggest Java Object Layout tool (https://github.com/openjdk/jol) or related extension for IntelliJ Idea (https://github.com/stokito/IdeaJol). In case of this example, it shows that resulting class looks like this in memory:
Instance size 24 Losses total 10 Losses internal 3 Losses external 7
Offset Size Type Class Field
0 12 (object header)
12 1 boolean A attribute < private field of A
13 3 (alignment/padding)
16 1 boolean B attribute < private field of B
17 7 (loss due to the next object)
Upvotes: 7