Java Constructors- Using super()

April 25, 2014 | Constructors
The magic of super()

We have seen earlier, the usage of this() statement where it is used to call in between the constructors belonging to the same class. Here no inheritance is involved. Now in this posting, let us learn how to call a super class constructor from subclass constructor.

Example on super()
class Animal
{
  public Animal()			// I
  {
    System.out.println("All animals eat");
  }
  public Animal(String name1)		// II
  {
    System.out.println("Animal name is " + name1);
  }
}

public class Lion extends Animal
{
  public Lion()			        // III
  {
    System.out.println("Lion eats other animals");
  }
  public Lion(String name1)		// IV
  {
    super("Bushy Animal");
    System.out.println("Lion name is " + name1);
  }
  public static void main(String args[])
  {
    Lion l1 = new Lion("King");		// calls IV
  }
}

super()

super("Bushy Animal");

super() statement is used to call super class constructor from subclass constructor. One object of l1 is created in main() method calling IV constructor. super("Bushy Animal") written in IV with string parameter calls super class matching constructor; it is obviously II. Instead of super("Bushy Animal"), if just super() is written, the IV will call I (ofcourse, it is the default behaviour also).

Using both this() and super() in one program.

Now let us call all the 4 constructors, 2 from super class and 2 from subclass with one subclass object creation. Just modify the previous code.

Before going into the code know this() Vs super(), just remember this() calls same class constructor and super() calls super class constructor.

Example on this() and super() usage
class Animal
{
  public Animal()			// I
  {
    System.out.println("All animals eat");
  }
  public Animal(String name1)		// II
  {
    this();
    System.out.println("Animal name is " + name1);
  }
}

public class Lion extends Animal
{
  public Lion()			        // III
  {
    super("Bushy Animal");
    System.out.println("Lion eats other animals");
  }
  public Lion(String name1)		// IV
  {
    this();
    System.out.println("Lion name is " + name1);
  }
  public static void main(String args[])
  {
    Lion l1 = new Lion("King");		// calls IV 
  }
}

super()

In the main(), IV constructor is called. in IV, this() is written which calls the III of the same class. In III, super("Bushy Animal") is written which calls matching super class constructor II with string parameter. In II, this() is written which calls same class matching constructor I (that without parameter).

The order of calling is IV, III, II and I. The output will be in reverse order.