Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Ways to Implement Java Constructor Chaining
3.
Why Do We Need for Constructor Chaining?
4.
Rules For Constructor Chaining
5.
Working of Constructor Chaining in Java
6.
Constructor Calling from Another Constructor
7.
Example of Constructor Chaining In Java
7.1.
Calling The Current Class Constructor
7.2.
Java
7.3.
Calling the Calling Super Class Constructor
7.4.
Java
8.
Frequently Asked Questions
8.1.
What's the difference between overloading constructors and chaining constructors?
8.2.
In Java, what is a constructor?
8.3.
Is it feasible to override a constructor in Java?
8.4.
Is constructor chaining and overloading the same?
8.5.
What is explicit and implicit constructor chaining in Java?
9.
Conclusion
Last Updated: May 17, 2024
Easy

Constructor Chaining In Java

Author Akshit Pant
0 upvote
Roadmap to SDE career at Amazon
Speaker
Anubhav Sinha
SDE-2 @
25 Jun, 2024 @ 01:30 PM

Introduction

Constructor chaining is a powerful concept in Java that allows constructors within a class to call other constructors in the same class or in its superclass. This technique helps in reusing code and simplifying initialization processes by ensuring that common initialization logic is centralized and not duplicated across multiple constructors. In this blog, we'll explore the concept of constructor chaining in Java.

Constructor Chaining In Java

Constructor chaining in Java refers to the process of one constructor calling another constructor within the same class or in its superclass. This allows for reusing initialization logic and ensuring that common setup tasks are not duplicated across multiple constructors. Constructor chaining helps in maintaining clean and concise code by centralizing initialization processes and promoting code reuse.

Ways to Implement Java Constructor Chaining

There are two ways to chain constructors:

  1. Within the Same Class: In this approach, a constructor in a class can call another constructor in the same class using the this() keyword. This allows for reusing initialization logic and ensuring that multiple constructors within the class share common setup tasks.
  2. From Base Class: When extending a class in Java, constructors in the subclass can chain constructors from the base class using the super() keyword. This allows for leveraging the initialization logic defined in the superclass constructors while adding additional functionality specific to the subclass. It promotes code reuse and maintains the inheritance hierarchy.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Why Do We Need for Constructor Chaining?

The actual benefit of Constructor Chaining is that you can feed parameters via many constructors while only having to do the initialization only once in a single place. 
Constructor chaining is used in Java programming when we wish to conduct numerous tasks in a separate constructor for each task and organize them by chaining. This method makes the application more readable and understandable for all users.
Within the class, we may specify as many constructors as we like and utilize constructor chaining to connect them.

Rules For Constructor Chaining

Following are the rules to keep in mind while doing Constructor Chaining:

  • If an expression uses this keyword, then this() expression must be the first line of the constructor.
  • When chaining constructors, the order doesn't matter.
  • There must exist at least a single constructor without this keyword.

Now we know that calling the constructor can be done in two possible ways:
Using this() keyword for constructors within the same class and using the super() keyword for calling the constructor from the base class.

Note: We can't use this() and super() at the same time in the same constructor block/section.
Now, let us see the implementation of Constructor Chaining with working examples given below.

Also read, Swap Function in Java

Working of Constructor Chaining in Java

Constructor chaining in Java involves one constructor calling another constructor within the same class or in its superclass. When a constructor is called, it initializes the instance variables and executes the initialization code. If another constructor is called using this() or super() keyword, the control transfers to the called constructor, which executes its initialization code, and so on. This process continues until the chain reaches the final constructor. Below is the diagram illustrating the concept:

Working of Constructor Chaining in Java

Constructor Calling from Another Constructor

1. Using this() method:

  • Constructor1 calls Constructor2 using this().
  • this() must be the first statement in the constructor.

Example:

Constructor1(int x) {
 this(x, 0); 
 }
 Constructor2(int x, int y) {
 // Initialization code 
 }

2. Using super() method:

  • Subclass constructor calls superclass constructor using super().
  • super() must be the first statement in the subclass constructor.

Example:

SubclassConstructor(int x) { 
super(x); 
}
SuperclassConstructor(int x) {
 // Initialization code 
 }

Example of Constructor Chaining In Java

In the first example, We are implementing Constructor Chaining within the same class with this() keyword.

Calling The Current Class Constructor

If we wish to invoke/call the current class constructor from within the same class, we utilize this() keyword. The this() keyword must be used since JVM never adds it automatically like the super() keyword does. Note that this() keyword must be the first line of the constructor, and there must exist at least one constructor without the keyword this().

Code:

  • Java

Java

class myClass     // myClass is the class name for making constructors
{
   myClass()
   {
       this(100); // calling constructor2
       System.out.println("Printing the Default constructor here");
   }

   myClass(int i) // this is parameterized constructor2
   {
       this(200, 500); // calling constructor3
       System.out.println(i);
   }

   myClass(int i, int j) // this is parameterized constructor3 with no this() keyword
   {
       System.out.println(i + j);  // simple printing
   }

   public static void main(String args[]) // main method
   {
       new myClass(); // invoking the default constructor
   }
}

We made an instance of the class in the preceding example without supplying any parameters. It first invokes the default constructor(myClass()), and the default constructor redirects the call to the parameterized constructor2 because of this(). The constructor2 redirects the call to constructor3, and the statements inside the parameterized constructor3 are executed, followed by statements of constructor2, and then the call returns back to the default constructor. The rest of the default constructor statements are then executed, and the object is successfully initialized.

Output:

700
100
Printing the Default constructor here

Calling the Calling Super Class Constructor

Whenever we need to invoke the constructor of superclass (parent class) from a child class (derived class), we utilize the super() keyword in the derived class constructor. It is not necessary to write super() because JVM does so automatically. If we try to call a superclass constructor from a child class, we get a syntax error.

  • super(): It invokes the superclass's no-argument or default constructor.
  • super(parameters): It calls the parameterized constructor of the superclass.

Remember that the constructor of the superclass cannot be inherited by the subclass. The super keyword can be used to invoke it from the constructor of a subclass.

Let's make a Java program and use an inherited class to implement constructor chaining.

Code:

  • Java

Java

class myClass         // class for base constructors
{
   String myStringName;


   myClass()  // this is base class constructor1
   {
       this("");
       System.out.println("No-argument constructor of" +
                                          " base class");
   }
 
   myClass(String myStringName)  // this is base class constructor2 with parameter
   {
       this.myStringName = myStringName;
       System.out.println("Calling out the parameterized constructor"
                                             + " of the base class");
   }
}

class myDerivedClass extends myClass
{
 
   myDerivedClass() // this is derived class constructor 3 with no patrameters
   {
       System.out.println("No-argument constructor " +
                          "of derived");
   }

 
   myDerivedClass(String myStringName) // this is parameterized constructor4 of derived class
   {
     
       super(myStringName);  // this invokes base class constructor2
       System.out.println("Calling the parameterized " +
                          " & this is constructor of derived");
   }

   public static void main(String args[])  // main method
   {
   myDerivedClass obj = new myDerivedClass("papers");  // calling the parameterized constructor4
   }
}

First, we entered the main() method, which redirected us to parameterized constructor4 of the derived class. The super() statement of constructor4 invoked the base class(myClassconstructor2. Its statements get executed, then the call returns back to derived class constructor4, and its statement execution ends our program.

Output:

Calling out the parameterized constructor of the base class
Calling the parameterized  & this is constructor of derived

Here, super() should be the first line of the constructor, similar to constructor chaining in the same class because the super class's constructor is called before the sub class's constructor and try this code by yourself on online java compiler.

You can also read about the Multiple Inheritance in Java and Hashcode Method in Java

Frequently Asked Questions

What's the difference between overloading constructors and chaining constructors?

Constructor overloading allows a class to have many constructors with the same name but differing only in terms of the number or type of parameters.
With respect to the current object, constructor chaining is the process of calling one constructor from another constructor.

In Java, what is a constructor?

In Java, a constructor is equivalent to a method that is called when a class object is formed. A constructor, unlike Java methods, has the same name as the class and does not have a return type.

Is it feasible to override a constructor in Java?

Constructor appears to be a method, but it isn't. It doesn't have a return type, and its name is identical to that of the class. But, the constructor cannot be overridden.

Is constructor chaining and overloading the same?

No, constructor chaining and overloading are not the same. Constructor chaining involves one constructor calling another constructor within the same class or superclass, while overloading involves defining multiple constructors with different parameter lists within the same class.

What is explicit and implicit constructor chaining in Java?

Explicit constructor chaining in Java involves calling another constructor using this() or super() keyword within a constructor. Implicit constructor chaining occurs when a constructor does not explicitly call another constructor, and Java automatically invokes the superclass's default constructor if no explicit call is made using super().

Conclusion

This article taught us about Constructor Chaining In Java. It is a powerful feature that allows constructors within a class to call other constructors within the same class or in its superclass. It promotes code reuse, simplifies initialization processes, and ensures that common setup tasks are centralized. By leveraging constructor chaining effectively, Java developers can write cleaner, more maintainable code and enhance the flexibility and scalability of their applications.
You can head over to our Android Development Course to dive deep into Android Development and build future applications.
Check out this problem - Longest String Chain
We hope this article has helped you enhance your knowledge of the Android Listeners, Handlers, and Registration. If you want to learn more, check out our Programming Fundamentals and Competitive Programming articles. Do upvote this article to help other ninjas grow.

Previous article
Order of execution of constructors in java inheritance
Next article
Method Overloading and Method Overriding
Live masterclass