Inheritance and Default Base Class Constructors

Contact Us or call 1-877-932-8228
Inheritance and Default Base Class Constructors

Inheritance and Default Base Class Constructors

One base class constructor will always run when instantiating a new derived class object.

  • If you do not explicitly call a base class constructor, the no-arguments base constructor will be automatically run, without the need to call it as super().
  • But if you do explicitly call a base class constructor, the no-arguments base constructor will not be automatically run.
  • The no-arguments (or no-args for short) constructor is often called the default constructor, since it is the one that will run by default (and also because you are given it by default if you write no constructors).

Code Sample:

Java-Inheritance/Demos/Inheritance2.java
class Purple {
  protected int i = 0;
  public Purple() {
    System.out.println("Purple() running and i =  " + this.i);
  }
  public Purple(int i) {
    this.i = i;
    System.out.println("Purple(i) running and i = " + this.i);
  }
}

class Violet extends Purple {
  Violet() {
    System.out.println("Violet() running and i = " + this.i);
  }
  Violet(int i) {
    System.out.println("Violet(i) running and i = " + this.i);
  }
}

public class Inheritance2 {

    public static void main(String[] args) {
    System.out.println("new Violet():");
    new Violet();

    System.out.println();
    System.out.println("new Violet(4):");
    new Violet(4);
  }
}

Each constructor prints a message so that we can follow the flow of execution. Note that using new Violet() causes Purple() to run, and that new Violet(4) also causes Purple() to run.

For the sake of simplicity, the i field has been made protected, but this is not considered a good practice.

If your base class has constructors, but no no-arguments constructor, then the derived class must call one of the existing constructors with super(args), since there will be no default constructor in the base class.

If the base class has a no-arguments constructor that is private, it will be there, but not be available, since private elements are hidden from the derived class. So, again, you must explicitly call an available form of base class constructor, rather than relying on the default.

Try the above code with the Purple() constructor commented out or marked as private.

Next