Do you think IIT Guwahati certified course can help you in your career?
No
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 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:
Within the Same Class
From Parent/Base Class
Constructor Chaining 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.
Two-parameter constructor called
Single-parameter constructor called
Default constructor called
Name: Unknown, Age: 0
Constructor Chaining From Parent/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.
Example
Java
Java
class Animal { String species;
// Constructor in base class public Animal(String species) { this.species = species; System.out.println("Animal constructor called"); } }
class Dog extends Animal { String breed;
// Constructor in subclass public Dog(String species, String breed) { super(species); // Calls the constructor of the base class this.breed = breed; System.out.println("Dog constructor called"); }
public void display() { System.out.println("Species: " + species + ", Breed: " + breed); } }
public class ConstructorChainingBaseClass { public static void main(String[] args) { Dog dog = new Dog("Mammal", "Golden Retriever"); dog.display(); } }
You can also try this code with Online Java Compiler
Animal constructor called
Dog constructor called
Species: Mammal, Breed: Golden Retriever
Why Do We Need for Constructor Chaining?
Code Reusability: Avoids duplication by reusing initialization logic across constructors.
Consistency: Ensures all constructors share common setup steps, reducing errors.
Simplified Maintenance: Changes to initialization logic need to be made in only one place.
Supports Inheritance: Ensures the superclass constructor is called before subclass-specific initialization.
Improves Readability: Cleaner and more structured code, making initialization logic easier to follow.
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.
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:
Constructor Calling from Another Constructor
1. Using this() method:
Constructor1 calls Constructor2 using this().
this() must be the first statement in the constructor.
In the first example, We are implementing Constructor Chaining within the same class with this() keyword.
Example 1: 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 thekeyword 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 } }
You can also try this code with Online Java Compiler
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
Example 2: 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 } }
You can also try this code with Online Java Compiler
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(myClass) constructor2. 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.
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.
Why do we chain constructors?
We chain constructors to reuse initialization logic, avoid code duplication, and maintain consistency. It simplifies maintenance, ensures proper object setup, supports inheritance by initializing superclasses first, and enhances readability by centralizing common setup tasks.
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. Recommended Article: