In this article we will discuss what happens when a class inherits a class with constructor. The constructor is a special method, and it is not inherited to the subclass like normal methods.
Thus, the inheritor class can define its own constructor that is fully independent from the definition of the constructor in its superclass. However, it is mandatory to call the immediate superclass constructor in the implementation of the subclass constructor. Thus, it will be good practice to add all parameters of superclass constructor signature in the subclass constructor signature. In addition, the subclass constructor can add its own parameters.
Various scenarios are possible when it comes to Constructor inheritance:
Scenario 1: Static constructor defined in superclass. Static constructor defined in subclass.
- When the subclass is accessed for the first time, first the superclass static constructor is executed, immediately followed by the subclass static constructor.
Scenario 2: Super class has static and instance constructor defined. No constructor defined in subclass
- From previous constructor knowledge, you should be aware that on first object creation of superclass, first the static constructor and then the instance constructor will be invoked automatically by the runtime.
- For every further object creation of superclass, only the instance constructor will be called.
- Now, if an object of subclass is created, only the instance constructor of superclass will be called.
- However, if you are creating a subclass object without any call to static components or any superclass object creation, then first the static constructor and then the instance constructor of superclass will be called.
- On further creation of subclass object, the instance constructor will be invoked.
Scenario 3: Both Superclass and Subclass has both instance and static constructor defined.
- In this case, when the subclass is accessed for the first time, first the superclass static constructor will be called, followed by subclass static constructor, and then followed by superclass instance constructor and finally subclass instance constructor.
Example 1
Example 2
Example 3