How Constructor Chaining works in Java - Example

How to call one constructor from another constructor in Java or What is Constructor Chaining in Java is one of the tricky questions in Java interviews. Well, you can use this keyword to call one constructor from another constructor of the same class if you want to call a constructor from based class or super class then you can use super keyword. Calling one constructor from other is called Constructor chaining in Java. Constructors can call each other automatically or explicitly using this() and super() keywords. this() denotes a no-argument constructor of the same class and super() denotes a no argument or default constructor of parent class. Also having multiple constructors in the same class is known as constructor overloading in Java.


How Constructor chaining works in Java

How Constructor Chaining works in JavaAs I said Constructor can be call other constructors automatically or explicitly. If you do not call any constructor either from the same class or super class than Java compiler will call super() i.e. no argument constructor of Parent class. Also, call to another constructor must be the first line in Constructor. Suppose you want to call another constructor of the same class which accepts an int argument, you can use this(1) to call that constructor. 

Similarly if that constructor is in the super class, you can use super(1) to call that constructor. You can not call more than one constructor from a constructor in Java because every constructor call must be the first statement. 

Also if you don't declare any constructor in your class, Java will add a default or no argument constructor in your class. In next section, we will see an example of how to call one constructor from other in Java.




Constructor Chaining Example in Java
Here is a code example of constructor chaining in Java. In this Java program, we show how to call the constructor using both this and super keyword. this() calls the constructor from the same class and super() calls constructor from the parent class in Java.

/**
 *
 * Java program to demonstrate How constructor chaining in Java.
 * When one constructor calls other in Java then it referred as Constructor chaining.
 * this and super keywords are used to call a constructor from another constructor.
 *
 * @author http://java67.blogspot.com
 */

public class ConstructorChaining{

    public static void main(String args[]) {
           // testing constructor chaining in Java
           Derived sub = new Derived("Test");
    }
}

class Base{
    protected String name;
 
    public Base(){
        this(""); //calling one arg constructor of same class
        System.out.println("Inside no argument constructor of Base class");
    }
 
    public Base(String name){
        this.name = name;
        System.out.println("One arg constructor of Base class");
    }
}

class Derived extends Base{
 
   public Derived(){
       System.err.println("Inside no argument constructor of Derived class");
   }
 
   public Derived(String name){
       super(name); //calling one argument constructor of super class
       System.out.println("Inside one arg constructor from Derived class");
   }
}

Output
One arg constructor of Base class
Inside one arg constructor from Derived class


In this example, we create an instance of a Derived class by calling the constructor of the Derived class which accepts a String argument, that constructor than class to one argument constructor of super class. This is an example of explicitly calling one constructor from other in Java. To demonstrate automatic constructor chaining let's see another example

Derived sub = new Derived();

Output
One arg constructor of Base class
Inside no argument constructor of Base class
Inside no argument constructor of Derived class

In this example, we are calling no argument constructor of Derived class which automatically calls no argument constructor of Superclass, which is Base in this case, which in turn call String argument constructor of Base class. Since there is no explicit constructor call on Derived class no argument constructor it by default calls to super().

Important points about Constructor chaining in Java
Here are few worth noting points about Constructor chaining in Java, which is core of calling one constructor from other in Java program :

1) Call to another constructor of same class or parent class must be the first statement in the constructor.

2) If you do not call another constructor either from parent class or same class than Java calls default or no argument constructor of super class.

3) If you do not declare any constructor in Java then Java compiler adds a default or no argument constructor in your class, which by default calls no argument constructor of super class. If you don't have a no-argument constructor in superclass then this would result in compile time error. That's why we should always have a no argument constructor in our class.

That's all on What is Constructor Chaining in Java and How constructor chaining works in Java. Just remember that this() and super() can be used to explicitly call constructor of same class and constructor of parent class in Java. It's also worth remembering points mentioned about special behaviors of Constructor in Java.

Happy New Year to All of You !!!

Other Java programming tutorials for programmers

6 comments:

  1. Thank you for this!

    ReplyDelete
  2. What is the need for this chaining any way?

    ReplyDelete
  3. I am using eclipse IDE and I have not declare any default constructor in both class then also I am successfully able to execute my program. I don't know where default constrcutor is needed ? Is it I am not getting compile time error because I m using IDE

    package com.corejava.oops;

    class ABC{
    void add(){
    System.out.println("Add");
    }
    }

    class BCB extends ABC{
    void add(){
    System.out.println("BCB Add");
    }
    void add1(){
    System.out.println("BCB Add1");
    }
    }
    public class NoArugmentCostructorBothSuperAndSubClass {
    public static void main(String args[]){
    ABC a = new BCB();
    a.add();
    BCB b = new BCB();
    b.add1();
    }
    }

    ReplyDelete
    Replies
    1. Java implicitly adds a no argument constructor in your class. That's why no compile time error.

      Delete
    2. Check the .class file you shall see the default constructor created in your file.

      Delete
  4. Why does another constructor call has to be the first statement?

    ReplyDelete