Monday, September 25, 2023

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 a based class or super class then you can use the super keyword. Calling one constructor from another 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 the 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 called other constructors automatically or explicitly. If you do not call any constructor either from the same class or super class then the Java compiler will call super() i.e. no-argument constructor of Parent class.

 Also, a 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 the 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 the constructor from the parent class in Java. 

You can further see these free Java courses to learn more about essential Java concepts like this. 

/**
 *
 * Java program to demonstrate How constructor chaining in Java.
 * When one constructor calls other in Java then it is referred to 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 then 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 the no-argument constructor of Derived class which automatically calls the no-argument constructor of Superclass, which is Base in this case, which in turn calls 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 a few worth noting points about Constructor chaining in Java, which is core of calling one constructor from another 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 superclass. 

If you don't have a no-argument constructor in superclass then this would result in a 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 the constructor of same class and constructor of the parent class in Java. It's also worth remembering the points mentioned about the special behaviors of Constructors in Java.



Other Java programming tutorials for programmers

Thanks for reading this article so far. If you like an object-oriented programming tutorial then please share it with your friends and colleagues. If you have any questions or feedback then please drop a note.

And lastly one question for you,  what is the return type of Constructor in Java? 

10 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
  5. Whats the real need for providing a super() calling by jvm..when we can call explicitly.

    ReplyDelete
    Replies
    1. In java the parent class is initialized internally first before the derived calls is initialized so internally derived class has to make an implicit call if needed to super().

      Delete
  6. There should be super() call inside Derived() default constructor.

    ReplyDelete
    Replies
    1. but isn't that's the implicit call? you don't need to declare that unless you are a calling a parametric constructor.

      Delete

Feel free to comment, ask questions if you have any doubt.