When instantiating a Java object, is an object of the parent class created automatically?

StackOverflow https://stackoverflow.com/questions/19313938

  •  30-06-2022
  •  | 
  •  

Question

Suppose I create an object, and one constructor of the parent class is run. With this constructor a new object of the parent is created as well behind the scenes?

If not, where are the private fields of the parent class stored? You can actually call any method of the parent object (with or without super) which operates of the private fields invisible of the calling object.

If anyone who is most familiar with the Java Memory Model, his or her answer is very welcome!

Was it helpful?

Solution

With this constructor a new object of the parent is created as well behind the scenes?

No, only one instance is created. The created instance contains the attributes of the current class and all of 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 terms of memory location if they are defined in the current class or the superclass.

OTHER TIPS

It doesn't create two objects, only subclass object.

When inheriting from another class, you must call super() in your constructor. If you don't, the compiler will insert that call for you as you can plainly see.

The superclass constructors are called because otherwise the object would be left in an uninitialized state.

Remember inheritance is an "is a" relationship between the base class and the subclass, thus every 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, not as two separate instances). To initialize the base class properly the constructor is called.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top