How to perform constructor chaining in java with example

Before trying to understand constructor chaining, it is suggested to understand what a constructor is, in case you are not familiar.
What is constructor chaining
Constructor chaining means calling one constructor from another constructor. It can occur within same class or more than one classes having parent-child relationship.
Constructor chaining can be done by the programmer or automatically by the compiler as you will learn in this article.


Use of constructor chaining
If you have multiple constructors and most of the constructors share the same piece of code, then constructor chaining is of great help.
You can create a constructor containing the common code and invoke that constructor from all the constructors using this and the required arguments expected by the common constructor.
Constructor chaining in same class
It happens when one constructor calls another constructor of the same class. Constructor chaining in same class is done using this keyword followed by parenthesis, just like a method in java is invoked.
Parenthesis after this() contain the parameters that are expected by the constructor being called. Example program for this type of chaining is given below.

public class ConstructorChainingExample {
 
   String message;
   /*
   * No argument constructor
   */
   public ConstructorChainingExample() {
      // call other constructor
      this("Default message");
   }
 
   /*
   * Single argument constructor
   */
   public ConstructorChainingExample(String m) {
      this.message = m;
   }
}

In the above example, there are two constructors. No argument constructor calls the constructor expecting a String as a single argument with some default value.


Constructor chaining in different class
A constructor of a class may call a constructor of its parent class. This is done by using super keyword followed by parenthesis along with the arguments, if the parent class constructor expects any.
This is similar to calling a method in java. Remember that a constructor can only call a constructor of its parent class, not of its child classes. This makes sense since a parent constructor does not know anything about its child classes.
Example program for a constructor calling its parent class constructor is given below.

public class Parent {
 
   String message;
   /*
   * No argument constructor
   */
   public Parent() {
      // call other constructor
      this("Default message");
   }
 
   /*
   * Single argument constructor
   */
   public Parent(String m) {
      this.message = m;
   }
}
 
public class Child extends Parent {
   public Child() {
      // call parent class constructor
      super("From child");
   }
 
}


Constructor chaining rules
A. First statement in a constructor should be either a call to this() or super(). Thus, below constructor is invalid.

public class InvalidConstructor {
 
   public InvalidConstructor() {
      System.out.print("First statement");
      super();
   }
}

Above code will result in a compiler error Constructor call must be the first statement in a constructor.
B. If you do not write a this() or super() as the first statement, the compiler does it for you. Consider below constructor

public class ConstructorExample {
 
   public ConstructorExample() {
      System.out.print("First statement");
   }
}

Compiler will convert it to

public class ConstructorExample {
 
   public ConstructorExample() {
      // implicit call to parent class constructor
      super();
      System.out.print("First statement");
   }
}

C. Compiler automatically inserts a call to super() and invokes the no-argument constructor of parent class.
If the child class constructor does not call another constructor(either of same class using this() or of a parent class using super()), then the parent class should have a no argument constructor.
Thus, below example will be a compiler error.

public class Parent {
   public Parent(String m){
      System.out.print("Parent constructor");
   }
}
 
public class Child {
   public Child() {
      System.out.print("Childconstructor");
   }
}

This is because child constructor will try to invoke the no-argument constructor of parent class which is not present. Remember that compiler will only add a no-argument constructor when no other constructor is present.
Above example can be corrected in any of the following ways

  1. Add a no argument constructor to the parent class.
  2. Remove the constructor from parent class. This is because if no constructor is present in a class, then the compiler automatically provides a default constructor, which is a no-argument constructor.

    To learn about default constructor, refer this article.

  3. Modify the child class constructor so that it explicitly calls parent constructor as below.
    public Child() {
       super("Calling parent");
       System.out.print("Childconstructor");
    }



D.
If your class does not extend a class, then the constructor of java.lang.Object will be invoked since it is the parent class of all classes.
E. Automatic calling of parent class constructor happens till the top most parent constructor. That is, when you create an object using a constructor, then all the constructors of the parent classes till java.lang.Object are invoked.
F. If a class has multiple constructors, then you cannot insert a this() in all of them. This will result in an infinite recursive chain as each constructor will keep on calling another.
Constructor Chaining vs. Constructor overloading
Both terms have different meanings. Below are the differences.

  • Constructor overloading means having more than one constructor with different number or types of arguments or both while constructor chaining means invoking one constructor from another.
  • Constructor overloading can only occur in same class while constructor chaining occurs in same and parent classes.
  • Constructor chaining can also be done implicitly by the compiler when it calls default constructors of parent class while constructor overloading can not be done automatically by the compiler.

Hope this article helped you to understand the concept of constructor chaining in java. Hit the clap button below to like it.

0

Mark Your Impression

Close Menu