Inheritance of constructors in java

592 Views Asked by At

Whenever any constructor is called in any derived class the task gets accomplished only by eventually calling the base class constructor implicitly or explicitly (correct me if I am wrong here).

Since we intended to create an instance of the derived class, but since the base class constructor is called in the end.

So, how is an instance of the derived class is constructed despite the constructor of base class being called upon?

2

There are 2 best solutions below

1
On BEST ANSWER

Don't think of the constructor as creating the instance. Think of it as initializing the instance, with respect to that particular class.

So the initialization process looks something like:

  • Allocate memory
  • Initialize object from perspective of java.lang.Object
  • Initialize object from perspective of your.package.Superclass
  • Initialize object from perspective of your.package.Subclass

(Even though you start with a call to new Subclass(...), the superclass constructor body is executed first.)

The details of object initialization are given in JLS section 12.5.

0
On

Constructor is not very fortunate name. It may suggest that it is responsible for creating (constructing) object, but in reality it is responsible for initialization of already existing object.

Object is created by new operator. But that object is "set up" to have all its fields filled with default values: null, false, 0 (depending on type). To make such object usable in our application we need to "set it up" (initialize) properly and that is the job of constructor.

But since classes can extend other classes it is required from constructors of subclass to execute its code only after execution of constructor of superclass (for instance to make sure that all inherited fields are properly initialized so we could use in our constructor inherited methods which actually use those superclass fields). Which is why super(..) call is placed explicitly or implicitly at start of every constructor (except Object class since it doesn't extend other class).