Lets say I have a class A.java,

When I will execute a constructor method of A, it will create a memory space for xyz Object.
A xyz = new A();
The reference to memory may be something like,
[xyz] ---> '0x34524'
Thats basics of OOP. Simple enough!
Now,
What happens if a class is inheriting from different parent classes? How many object space will be created in memory?
Lets say we have,

and then we create an object of class D.java,
D omg = new D();
Here as we know that D’s object will call construct of C.java and so on until A.java. Does this mean that in memory we are having 4 different memory reference, because we are instantiating all of the four objects (one directly and another 3 indirectly)?
[omg] ---> '0x34525'
[C] ---> '0x34526'
[B] ---> '0x34527'
[A] ---> '0x34528'
Note :
- This isn’t homework question, this is just a curiosity question.
- I am aware of the fact that if we have a instance variable inside an A.java then we will not create only object A but we will be creating other internal object whenever we hit
newkeyword.
First, a tid bit… calling the constructor of an object does not allocate it. In bytecode, the initialization
new Object()is expressed as something to the effect of…The
newinstruction takes care of allocating the space and acquiring a reference to the yet uninitialized object, while theinvokespecialhandles calling the constructor itself (which is internally compiled to avoidmethod named<init>, hence the descriptor<init>()V).Moving on, internals of object allocation and representation on the heap are entirely JVM specific. However, as far as I know, there is only one allocated object per allocated object, no matter its number of super classes. The object itself in memory has space for the instance fields of both its own class and its super classes. It must also have space for a virtual method table, in order to do virtual dispatch when performing virtual method calls (e.g. via
invokevirtual) for the object.Internally, the Oracle HotSpot JVM manages things called oops, or ordinary object pointers. You can read more about the HotSpot memory layout here. Feel free to browse the HotSpot source repository.