Rajinder Menu

Inheritance and Constructors



Constructors are not members of a class so they do not get inherited from superclass to subclass but we can call superclass constructor from subclass either implicitly or explicitly.


Implicitly calling of constructor

Consider following example

class Parent{
  
  int num;

  Parent(){
   
   this.num=10;
   System.out.println("In Parent constructor.");
  
  }
}
public class Child extends Parent{

 int i;

 Child(int i){

  this.i=i;
  System.out.println("In Child constructor.");

}

 public static void main(String[] args) {
  Child childObject= new Child(13);
 }
}

Output:

In Parent constructor.
In Child constructor.

Here in our code we have called Child constructor

Child(int i){
 ...
}

by statement

Child childObject= new Child(13);

The Child constructor called the Parent constructor despite that there is no call to Parent constructor in Child constructor. This is known as implicit calling of superclass constructor by subclass constructor.

This happens because if a constructor does not explicitly invoke a superclass constructor by using super() keyword the Java compiler automatically inserts a call to the no-argument constructor of the superclass in subclass.

So compiler has inserted a call Parent(); in Child constructor as:

Child(int i){
  Parent(); //autmatically inserted by compiler
  this.i=i;
  System.out.println("In Child constructor.");
}

But for the above code to work the superclass constructor must have a no-argument constructor present in it. If the super class does not have a no-argument constructor, you will get a compile-time error.

For example if Parent class would be like:

class Parent{
  int num;
  //no no-argument constructor is present
}

compiler will give error in this case.

Suppose Parent class would be like:


class Parent{
  
  int num;

  //no no-argument constructor present
  //parametrized constructor
  Parent(int num){
    this.num=num;
    System.out.println("In Parent constructor.");
  }
}

In this case also compiler would give error because there is no no-argument constructor present in Parent class despite that parameterized constructor is present.


Explicitly calling constructor

For explicitly calling superclass constructor from subclass we use the super keyword in the subclass. See here to learn more about this.


I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment