Java - Inheritance and Constructors

Introduction

Constructors are not members of a class and they are not inherited by subclasses.

class MySuper {
  public MySuper() {
    System.out.println("Inside MySuper() constructor.");
  }
}

class MySub extends MySuper {
  public MySub() {
    System.out.println("Inside MySub() constructor.");
  }
}

public class Main {
  public static void main(String[] args) {
    MySub cs = new MySub();
  }
}

Syntax

The following are examples of calling constructor of a superclass:

The keyword super refers to the immediate ancestor of a class.

You can call superclass constructors using the super keyword only as the first statement inside a constructor.

Call no-args constructor of superclass

super();

Call superclass constructor with a String argument

super("Hello");

Call superclass constructor with two double arguments

super(1.5, 8.2);

Compiler Injection of a super() Call to Call the Immediate Ancestor's no-args Constructor

class CSuper {
   public CSuper() {
        super();  // Injected by the compiler
        System.out.println("Inside CSuper() constructor.");
   }
}

Compiler Injection of a super() Call to Call the Immediate Ancestor's no-args Constructor

class CSub extends CSuper {
        public CSub() {
                super();  // Injected by the compiler
                System.out.println("Inside CSub() constructor.");
        }
}

Quiz