Inheritance and Constructors - the super Keyword

Contact Us or call 1-877-932-8228
Inheritance and Constructors - the super Keyword

Inheritance and Constructors - the super Keyword

Since a derived class object contains the elements of a base class object, it is reasonable to want to use the base class constructor as part of the process of constructing a derived class object.

Constructors are "not inherited". In a sense, this is a moot point, since they would have a different name in the new class, and can't be called by name under any circumstances, so, for example, when one calls new Integer(int i) they shouldn't expect a constructor named Object(int i) to run.

Within a derived class constructor, however, you can use super( parameterList ) to call a base class constructor. Note that:

  • It must be done as the first line of a constructor.
  • Therefore, you can't use both this() and super() in the same constructor function.
  • If you do not explicitly invoke a form of super-constructor, then super() (the form that takes no parameters) will run.
  • For the superclass, its constructor will either explicitly or implicitly run a constructor for its superclass.
  • So, when an instance is created, one constructor will run at every level of the inheritance chain, all the way from Object up to the current class.

Code Sample:

Java-Inheritance/Demos/Inheritance1.java
class MyBase {
  private int x;
  public MyBase(int x) {
    this.x = x;
  }
  public int getX() {
    return x;
  }
  public void show() {
    System.out.println("x=" + x);
  }
}

class MyDerived extends MyBase {
  private int y;
  public MyDerived(int x) {
    super(x);
  } 
  public MyDerived(int x, int y) {
    super(x);
    this.y = y;
  }
  public int getY() {
    return y;
  } 
  public void show() {
    System.out.println("x = " + getX());
    System.out.println("y = " + y);
  }
}

public class Inheritance1 {
  public static void main(String[] args) { 
    MyBase b = new MyBase(2);
    b.show();
    MyDerived d = new MyDerived(3, 4);
    d.show();
  }
}

The diagram below shows the structure of our improved classes:

Apparent memory allocation for expanded base and derived classes

  • A MyDerived object has two constructors available, as well as both the getX and getY methods and the show method.
  • Both MyDerived constructors call the super constructor to handle storage of x.
  • The show method in the derived class overrides the base class version.
  • Note that you can tell which class's version of show() is running by the different spacing around the = sign.
  • x from the base class is not available in the derived class, since it is private in MyBase, so the show method in MyDerived must call getX() to obtain the value.
Next