Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

Understanding Constructor Chaining in Java with Examples & Implementation

Updated on 08 June, 2023

5.88K+ views
9 min read

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.

Frequently Asked Questions (FAQs)

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

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

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

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

RELATED PROGRAMS