Anand Kumar
Anand Kumar

Reputation: 393

Object creation in Constructor chaining w.r.t Inheritance

When we create a instance of a class it will automatically call super class constructor one way or another. In Inheritance when we create an instance of of child class it also has reference of parent class fields which is invisible, how does it parent class field reference is pointed to Child class in Heap Area? For example when we create a instance of any class ( A ref = new A(); ), an object is created in heap memory (new A()) which is link to reference present in stack area (ref).

Similarly if i create n instance of a class does it mean that i am creating n different instance of Object class? As every class extends Object class by default.

Upvotes: 2

Views: 97

Answers (2)

josejuan
josejuan

Reputation: 9566

Maybe or not (but probably not). It's depend entirely of the especific JVM.

Usually only one table is allocated for each instanted object containing the type, methods and data.

See https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-2.html#jvms-2.7 for the Oracle JVM:

2.7. Representation of Objects

The Java Virtual Machine does not mandate any particular internal structure for objects.

In some of Oracle’s implementations of the Java Virtual Machine, a reference to a class instance is a pointer to a handle that is itself a pair of pointers: one to a table containing the methods of the object and a pointer to the Class object that represents the type of the object, and the other to the memory allocated from the heap for the object data.

Upvotes: 1

GhostCat
GhostCat

Reputation: 140457

Assume that some class B has some private fields x and y. In order to do "its job", to give the desired behavior when methods on B are called, those fields must of course exist in the "memory area" allocated for an instance of B.

Now, when B is extended by C, then of course, when you instantiate C, those fields x and y need to be allocated, too. You are correct about that.

But: that doesn't mean that you instantiate an "additional" B object for a C. It simply means that when the JVM allocates the memory for the C instance, it knows that there needs to be room for the inherited x and y fields.

And finally: the class Object does not have any fields. Therefore there is no additional memory overhead "because anything extends Object".

Upvotes: 5

Related Questions