Java Constructor Chaining Example and Implementation
In our previous article, we discussed what is a Constructor and Copy Constructor in Java. In this article, we will discuss Constructor Chaining in Java.
Constructor Chaining is the process of invoking one constructor from another constructor. It is very tricky to understand how to call a constructor from another constructor.
We can implement the Constructor Chaining in Java using either this keyword or the super keyword. Let’s start learning Constructor Chaining in Java.
What is Constructor Chaining in Java?
Constructor Chaining is the process of calling one constructor of a class from another constructor of the same class or another class using the current object of the class.
Ways to implement Java Constructor Chaining
There are two ways by which we can use constructor chaining in Java. These ways depend on whether we are using it in the same class or the different class.
- Using this keyword
- Using the super keyword
a. Constructor Chaining with this() keyword
If we want to call the constructor from the same class, then we use this keyword.
Suppose we want to call both default and parameterized constructor during the instantiation of the class, then we pass the parameter at the object creation and in that parameterized constructor, we will write this statement so that the default constructor will be called.
Let’s see an example to understand this:
package com.techvidvan.constructorchaining; class Example { //default constructor Example() { System.out.println("Inside Default"); } //Parameterized constructor Example(int n) { //calling default constructor this(); System.out.println("Inside Parameterized"); } } public class ThisExample { public static void main(String arg[]) { //calling the parameterized constructor Example obj = new Example(15); } }
Output:
Inside Default
Inside Parameterized
b. Constructor Chaining with super() keyword
If we want to call the constructor from the parent class, then we use the super keyword.
Thus when there is more than one class with the relationship of inheritance, we need to use the super keyword in the child class to call the constructor of the parent class.
We can call a constructor of the current class only with this(). For example:
package com.techvidvan.constructorchaining; class Parent { Parent() { System.out.println("Parent class default constructor"); } Parent(int x) { System.out.println("Parent class one-argument constructor"); } } class Child extends Parent { Child() { //by default the default constructor of Parent class is invoked System.out.println("Child class default constructor"); } Child(int x) { super(); // default constructor of Parent class is invoked System.out.println("Child class one-argument constructor"); } } public class SuperExample { public static void main(String arg[]) { Child obj1 = new Child(); Child obj2 = new Child(10); } }
Output:
Parent class default constructor
Child class default constructor
Parent class default constructor
Child class one-argument constructor
Need for Constructor Chaining in Java
Constructor Chaining in Java is used when we want to pass parameters through multiple different constructors using a single object.
Using constructor chaining, we can perform multiple tasks through a single constructor instead of writing each task in a single constructor.
Constructor chaining allows us to create a separate constructor for each task and make links or chains among them, so as to increase the readability of the code.
Suppose, If we do not perform chaining among constructors and they require a specific parameter, then we will need to initialize that parameter twice in each constructor.
Whenever you want to make changes in the parameter you will have to make changes inside each constructor.
Note: In Java, it is invalid and illegal to call the constructor directly by name. We have to use either of these two keywords to call a constructor.
Working of Constructor Chaining in Java
Constructor chaining happens with the process of Inheritance in Java. When we are dealing with the parent class constructor, then the constructor of the subclass will first call the constructor of the superclass.
This makes sure that the subclass is created with the initialization of the members of the parent class. The constructor chain continues until it reaches the constructor with the last chain.
But, we can not call more than one constructor from a single constructor. Let’s understand the working of constructor chaining with a diagram.
Rules for Constructor Chaining in Java
If you want to use Constructor Chaining in Java, you must follow the below rules:
- The this() and super() statement must always be the first statement inside the constructor.
- At least one constructor should be present in the class that has no this() keyword inside it.
- We can implement the constructor chaining in any order.
Constructor Chaining Example in Java
Let’s understand the code to implement constructor chaining in Java using both this and super keyword.
package com.techvidvan.constructorchaining; class Student { private String name; private int age; public Student() { this("Shreya"); //calling one-argument constructor of same class System.out.println("Inside no-argument constructor of the Base class"); } public Student(String name) { this.name = name; System.out.println("Inside the one-argument constructor of the Base class"); } public Student(String name, int age) { this.name = name; this.age = age; System.out.println("Inside the two-argument constructor of the Base class"); } } class MedicalStudent extends Student { public MedicalStudent() { System.out.println("Inside no argument constructor of the Derived class"); } public MedicalStudent(String name) { super(name); //calling one argument constructor of the base class System.out.println("Inside the one-argument constructor from Derived class"); } public MedicalStudent(String name, int age) { super(name, age); System.out.println("Inside the two-argument constructor of the Derived class"); } } public class Test { public static void main(String args[]) { // Testing constructor chaining in Java MedicalStudent sub = new MedicalStudent("Priya"); //caliing one-argument constructor MedicalStudent sub1 = new MedicalStudent("Deepak", 23); //caliing two-argument constructor } }
Output:
Inside the one-argument constructor of the Base class
Inside the one-argument constructor from Derived class
Inside the two-argument constructor of the Base class
Inside the two-argument constructor of the Derived class
What happens if we change the order of constructors?
Original Code:
package com.techvidvan.constructorchaining; public class Demo { Demo() { System.out.println("Default constructor"); } Demo(int x) { this(); System.out.println("One-argument constructor"); System.out.println(x); } Demo(int x, int y) { this(5); System.out.println("Two-argument constructor"); System.out.println(x * y); } public static void main(String args[ ]) { new Demo(8, 10); } }
Output:
Default constructor
One-argument constructor
5
Two-argument constructor
80
Code after changing the order of constructors:
package com.techvidvan.constructorchaining; public class Demo { Demo() { this(5); System.out.println("The Default constructor"); } Demo(int x) { this(5, 15); System.out.println("One-argument constructor"); System.out.println(x); } Demo(int x, int y) { System.out.println("Two-argument constructor"); System.out.println(x * y); } public static void main(String args[]) { new Demo(); } }
Output:
Two-argument constructor
75
One-argument constructor
5
The Default constructor
Alternative method of constructor chaining using init block
There are some programs, in which each constructor has at least the same line of code that executes each time of constructor call.
In this case, we can put these common lines of code inside the init block. This block always executes first before the execution of any constructor.
Let’s see how can we use this init block in our Java code:
package com.techvidvan.constructorchaining; public class InitDemo { // block to be executed before any constructor. { System.out.println("Inside init block"); } //Default constructor InitDemo() { System.out.println("Inside Default constructor"); } // parameterized constructor with one argument. InitDemo(int n) { System.out.println("Inside Parameterized constructor"); System.out.println(n); } public static void main(String[] args) { // Object creation by calling no-argument constructor. new InitDemo(); // Object creation by calling one-argument constructor. new InitDemo(10); } }
Output:
Inside init block
Inside Default constructor
Inside init block
Inside Parameterized constructor
10
Important points about Constructor chaining in Java
After having plenty of knowledge on the Constructor Chaining in Java, let’s discuss some important points about it that you must know:
1. The call statement to one constructor either by the this() or the super() keyword must always be the first statement inside any constructor.
2. If you do not write any constructor in your code, then Java automatically adds a default constructor inside the class.
Conclusion
Constructors are like methods in Java but they do not have any return type and they are called when the object of the class is created.
The invocation of one constructor from another constructor within the same class or different class is known as constructor chaining in Java.
If we have to call a constructor within the same class, we use ‘this’ keyword and if we want to call it from another class we use the ‘super’ keyword. These two different classes must be in the relationship of inheritance.
We understood the working of constructor chaining and also discussed the result of changing the order of constructors.
Do share your feedback in the comment section if you liked the article.