Programs

Understanding Constructor Chaining in Java with Examples & Implementation

In Java, Constructors can be understood as blocks of code used to initialise newly created objects. A constructor is similar to instance methods in Java. However, there is a crucial difference between Constructors and methods in Java – while methods have a return type, Constructors do not have any specific return type. Programmers often refer to Constructors as a special type of method in Java.

Constructors in Java have same name as the class, and they look like the following: 

public class myProgram{

   //This is the constructor

   myProgram(){

   }

   ..

}

When a constructor is called from within another constructor, that is when Constructor Chaining occurs in Java. However, before we dive deeper into Constructor Chaining, let’s first have a quick look at how Constructors work in Java, along with some examples to solidify your understanding. 

How Do Constructors in Java Work? 

To understand how Constructors work, let’s look at an example. Suppose we have a class named myProgram. Now, when we create the object of this class, we will have to write the following statement: 

myProgram obj = new myProgram()

As you can see, the new keyword used in the above example creates the object of myProgram and invokes a constructor to initialise this newly created object. 

If this sounds a little confusing to you, fret not. Let’s look at a simple constructor program in Java to better understand the working of Constructors in Java. 

Basic Constructor Program in Java

Look at the following piece of Java code that uses Constructors: 

public class Test{

   String book;

   //Constructor

   Test(){

      this.book = "A Catcher in the Rye";

   }

   public static void main(String[] args) {

      Test obj = new Test();

      System.out.println(obj.book);

   }

}

Output:

A Catcher in the Rye

In the above program, we have created an object named ‘obj’ of our class Program. Then, we printed the instance variable name of this newly created object. As you can see from the output, the output is the same as the value passed to ‘book’ during the Constructor’s initialization. 

What this shows is that the moment the obj object was created, the Constructor got automatically invoked. Here, we used the ‘this’ keyword to refer to the current object. There are more ways to do this, too, which we will talk about later in the article while discussing Constructor Chaining. 

With the basics of Constructor in Java settled, let’s move on to Constructor Chaining in Java and how it works! 

Chaining of Constructors Within a Single Class

But what is constructor chaining in Java involving a single class? Calling one constructor from another in the same class includes constructor chaining within that class. The “this” keyword is used in the syntax for constructor chaining within the same class. The current class instance is referred to when “this” is used. It is best to understand the usage of constructor chaining in Java with example.

Chaining Constructors from Base/Parent Classes

A class in Java can derive from another class; the derived class is referred to as a subclass, and the class from which it derives is referred to as a superclass. A subclass can have its own constructors and invoke those of its superclass.

A superclass constructor uses the term super(), followed by the required inputs. The super() keyword must always be present in the subclass constructor’s first line. 

Call from a Different Constructor, a Builder

Using the this() keyword, a constructor in Java can call another constructor from the same class. The first keyword in the constructor must always be the this() keyword, which can only be used to call another constructor of the same type.

Telephone Superclass Constructor

The super() keyword in Java allows subclass constructors to call the superclass’s constructor. The super() keyword, which can only be used to call the constructor of the subclass’s superclass, must always be the first line of the subclass constructor.

Java programs may behave differently if the constructors are arranged in a different sequence. If a class has many constructors and one of them uses the this() keyword to call another constructor, changing the order of the constructors can change how a program behaves.

A Different Way to Chain Constructors Using the Init Block

Using an initialisation block is another approach to constructor chaining in Java. A section of code known as an initialisation block runs before the constructor is called. The class’s instance variables can be initialised using this block.

Essentials of Constructor Chaining in Java

When we call a Constructor from another Constructor of the same class, what happens is known as Constructor Chaining. The primary purpose of doing Constructor Chaining is to pass parameters through a bunch of different constructors and only initialise them in one place. This way, you get a chance to maintain all of your initialisations in a single location while different constructors can be provided to the users.

If you don’t perform Constructor Chaining and two different Constructors require one parameter, you will need to initialise that parameter twice. Plus, every time the initialisation changes, you will need to make respective changes to all the constructors instead of just one. 

As a rule of thumb, you should always call Constructors with more arguments from Constructors that have fewer arguments. You also must be aware that we can overload multiple Constructors in the class. However, at the time an object is created, only one particular Constructor gets called. There can be quite a few situations while programming in Java where you would need to call multiple constructors from one another without creating different objects. This mechanism of invoking one Constructor from another constructor and when that involved Constructor invokes another constructor is known as constructor chaining.

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

There are two primary things that you should keep in mind regarding Constructor Chaining to ensure utmost clarity: 

  • The primary purpose of Constructor Chaining is to maintain the code. The idea is to help you write only one piece of code which can be reused across your program. This way, not only will your code be clean and readable, but it will also be a lot easier to manage with all the corrections and changes happening only to one location instead of all the Constructors. 
  • The Constructor that has been invoked does not create a separate object. Instead, it uses the currently running object to invoke another constructor. It is just like calling a different method inside your Constructor, except it is also a constructor.

As you saw in the earlier example, we used this keyword to access the parameters of the Constructor. Likewise, Constructor Chaining also requires primarily two keywords. Here are those two keywords: 

  • this – Its method representation calls a current class constructor.
  • super – Its method representation calls an immediate super or parent superclass constructor.

In addition, you should be aware of a couple of other important terms and definitions in terms of Constructor Chaining in Java: 

  • Constructor Invocation: When you invoke a Constructor, and that Constructor gets successfully invoked, it is known as Constructor Invocation. 
  • Constructor Execution: If on invoking Constructor, control starts executing the statements in the Constructor body. It is known as constructor execution.

Key Rules of Constructor Chaining in Java

With the basics of Constructor Chaining settled, let’s look at some essential rules of working with Constructor Chaining in Java: 

  • this() can only call the parameters belonging to the same Constructor.
  • super() can only call the immediate superclass Constructor.
  • this() and super() should be the first statement in the Constructor.
  • This () and super() can’t be used within the same Constructor since both individuals need to be first statements, which is not practically possible. 
  • You cannot add this() in all the Constructors of the same class, as there should be at least one Constructor without this() statement.
  • The invoking and executing of Constructors in Java happens oppositely. So, if the Constructors were called in the order A, B, C, then the execution will be in the C, B, A order. 

For example, here, we have two separate classes that are working by overloading different Constructors. We want to execute the constructors in 2, 1, 4, 3, 5 order.

To execute constructors in order, we need to call the constructors exactly in opposite order like 5, 3, 4, 1, 2, see in the below example.

class Parent
{
Parent()// 1
{
this("hello");
System.out.println("in Parent 0 arg constructor 1");
}
Parent(String msg)// 2
{
System.out.println("in Parent(String) constructor 2");
}
}
class Constructor extends Parent
{
Constructor()// 3
{
this(10);// calling 5 number constructor
System.out.println("in Constructor 0 arg constructor 3");
}
Constructor(String msg)// 4
{
super();//calling 1 number parent class constructor
System.out.println("in Constructor(String msg) arg constructor 4");
}
Constructor(int i)// 5
{
this("hello");//calling 4 number constructor
System.out.println("in Constructor(int i) constructor 5");
}
 // main() method
public static void main(String[] args)
{
Constructor cobj = new Constructor(); // calling 3 number constructor
}
}

Output:
in Parent(String) constructor 2  
in Parent 0 arg constructor 1
in Constructor(String msg) arg constructor 4
in Constructor(int i) constructor 5
in Constructor 0 arg constructor 3
Summing up all the concepts of Constructors and Constructor Chaining in Java with one final example: 
class Emp
{   
    public String EName;
    public int EEarnings;
    public String address;
    public Emp()
    {
        this("Rahul");
    }
    public Emp(String name)
    {
     this(name, 140035);
    }
    public Emp(String name, int sal)
    {
     this(name, sal, "New Delhi");
    }
    public Employee(String name, int sal, String add)
    {
     this.EName=name;
     this.EEarnings=sal;
     this.address=add;
    }
    void disp() {
     System.out.println("Name: "+EName);
     System.out.println("Salary: "+EEarnings);
     System.out.println("Address: "+address);
    }
    public static void main(String[] args)
    {
        Employee obj = new Employee();
        obj.disp();
    }
}

Output:

Employee Name: Rahul
Employee Salary: 140035
Employee Address: New Delhi

Conclusion

With that, we come to the end of this article. We hope this clarified your doubts on Constructor Chaining in Java and solidified your understanding further. At upGrad, we believe in helping students from around the globe reach their full potential and succeed in their careers. Our courses are designed keeping in mind both freshers and experienced professionals. 

One such course is upGrad’s Job-linked PG Certification in Software Engineering, specifically designed for first-time job seekers. Check out the course content and get yourself enrolled today! Learn all the relevant Software Engineering skills like Java, DSA, OODAP, JavaScript, MERN, AWS, etc., from industry experts and leading professionals. 

In Java constructor chaining, what's the difference between this() and super()?

The super() keyword calls a parent class constructor, whereas the this() keyword calls a constructor of the same class.

Is it possible to chain more than two constructors in Java?

Java allows for a maximum of two constructor chains. You can create more intricate objects and reduce code duplication by doing this.

When a constructor in Java calls itself, what happens?

A constructor in Java that calls itself will result in a stack overflow error and an indefinite loop.

How does the default constructor in Java look?

A default constructor in Java is one that accepts no inputs. If there isn't a constructor declared in the class, one is produced automatically.

Want to share this article?

Prepare for a Career of the Future

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

×
Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks