When you instantiate a Java object, is the object automatically created by the parent class?

Suppose I create an object and start one constructor of the parent class. Is this constructor also creating a new parent object off-screen?

If not, where are the private fields of the parent class stored? In fact, you can call any method of the parent object (with or without super ) that works with private fields that are invisible to the calling object.

If someone who is most familiar with the Java memory model, his or her answer is very welcome!

+6
source share
3 answers

Is this constructor also creating a new parent object off-screen?

No, only one instance is created. The created instance contains the attributes of the current class and all its superclasses.

If not, where are the private fields of the parent class stored?

Like all class attributes, they are stored on the heap. There is no difference in memory location if they are defined in the current class or superclass.

+10
source

It does not create two objects, only a subclass object.

When inheriting from another class, you must call super () in your constructor. If you do not, the compiler will insert this call for you, as you can clearly see.

Superclass constructors are called because otherwise the object will be left in an uninitialized state.

0
source

Remember that inheritance is the β€œis” relationship between the base class and the subclass, so each time you have an instance of a subclass, by definition you will also have an instance of the base class (as part of the instance, and not as two separate instances). To properly initialize the base class, the constructor is called.

0
source

Source: https://habr.com/ru/post/955754/


All Articles