Java - Inheritance - Multi level inheritance

Java

In this tutorial we will learn about multi level inheritance in Java programming language.

We have already covered what is inheritance and how to access inherited variables and methods from the child class in the previous tutorials.

And we have also learned about super keyword to call the constructor of the parent class from the child class.

When and how is the parent constructor called?

To call the parent constructor we use the super() in the child class.

If we don't use the super() to call the constructor of the parent class then default constructor of the parent class is called from the child class.

Example

In the following example we have class GrandParent which is inherited by the class Parent which gets inherited by class Child.

// three classes involved in inheritance
GrandParent
  |
  V
Parent
  |
  V
Child

Code

// grand parent class
class GrandParent {
  // constructor of GrandParent class
  GrandParent() {
    System.out.println("From inside the constructor of the GrandParent class.");
  }
}

// parent class
class Parent extends GrandParent {
  // constructor of Parent class
  Parent() {
    System.out.println("From inside the constructor of the Parent class.");
  }
}

// child class
class Child extends Parent {
  // constructor of Child class
  Child() {
    // calling the parent class constructor
    super();

    System.out.println("From inside the constructor of the Child class.");
  }
}

// the main class
public class Example {
  
  // the main method
  public static void main(String[] args) {

    // creating an object of the Child class
    Child obj = new Child();

  }
}

Output:

$ javac Example.java 
$ java Example
From inside the constructor of the GrandParent class.
From inside the constructor of the Parent class.
From inside the constructor of the Child class.

Explanation

So, in the above code we can see that the Child class is inheriting the Parent class which is inheriting the GrandParent class.

From inside the constructor of the Child class we are calling the constructor of the Parent class by using the super keyword.

If we look at the above output we can see that first the constructor of the GrandParent class is called. Then the constructor of the Parent class is called. And finally the constructor of the Child class is called.

Constructor of the parent class is automatically called from the child class even if we don't explicitly call it using super().