Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Developmentbreadcumb forward arrow iconUnderstanding Constructor Chaining in Java with Examples & Implementation

Understanding Constructor Chaining in Java with Examples & Implementation

Last updated:
4th Jun, 2023
Views
Read Time
9 Mins
share image icon
In this article
Chevron in toc
View All
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: 

Ads of upGrad blog
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.

Ads of upGrad blog

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. 

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.

Frequently Asked Questions (FAQs)

1In 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.

2Is 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.

3When 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.

4How 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.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Best Jobs in IT without coding
134274
If you are someone who dreams of getting into the IT industry but doesn’t have a passion for learning programming, then it’s OKAY! Let me
Read More

by Sriram

12 Apr 2024

Scrum Master Salary in India: For Freshers & Experienced [2023]
900305
Wondering what is the range of Scrum Master salary in India? Have you ever watched a game of rugby? Whether your answer is a yes or a no, you might h
Read More

by Rohan Vats

05 Mar 2024

SDE Developer Salary in India: For Freshers & Experienced [2024]
905069
A Software Development Engineer (SDE) is responsible for creating cross-platform applications and software systems, applying the principles of compute
Read More

by Rohan Vats

05 Mar 2024

System Calls in OS: Different types explained
5021
Ever wondered how your computer knows to save a file or display a webpage when you click a button? All thanks to system calls – the secret messengers
Read More

by Prateek Singh

29 Feb 2024

Marquee Tag & Attributes in HTML: Features, Uses, Examples
5134
In my journey as a web developer, one HTML element that has consistently sparked both curiosity and creativity is the venerable Marquee tag. As I delv
Read More

by venkatesh Rajanala

29 Feb 2024

What is Coding? Uses of Coding for Software Engineer in 2024
5054
Introduction  The word “coding” has moved beyond its technical definition in today’s digital age and is now considered an essential ability in
Read More

by Harish K

29 Feb 2024

Functions of Operating System: Features, Uses, Types
5132
The operating system (OS) stands as a crucial component that facilitates the interaction between software and hardware in computer systems. It serves
Read More

by Geetika Mathur

29 Feb 2024

What is Information Technology? Definition and Examples
5059
Information technology includes every digital action that happens within an organization. Everything from running software on your system and organizi
Read More

by spandita hati

29 Feb 2024

50 Networking Interview Questions & Answers (Freshers & Experienced)
5138
In the vast landscape of technology, computer networks serve as the vital infrastructure that underpins modern connectivity.  Understanding the core p
Read More

by Harish K

29 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon