Constructor chaining in Java refers to the process where one constructor calls another constructor within the same class or from a superclass. This helps in reducing code duplication and maintaining clarity.
There are two types of constructor chaining:
Using this():
In a class, you can call one constructor from another using the this()
keyword. This is useful when you want multiple constructors to share the same logic.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Person { String name; int age; // Constructor 1 public Person() { this("Unknown", 0); // Calls Constructor 2 } // Constructor 2 public Person(String name, int age) { this.name = name; this.age = age; } public void display() { System.out.println("Name: " + name + ", Age: " + age); } } public class Main { public static void main(String[] args) { Person person1 = new Person(); // Uses Constructor 1 Person person2 = new Person("John", 25); // Uses Constructor 2 person1.display(); person2.display(); } } //Output Name: Unknown, Age: 0 Name: John, Age: 25 |
Using super():
In inheritance, the subclass constructor can call a constructor from the superclass using super()
. This lets the subclass reuse the initialization logic from the parent class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Animal { String name; // Constructor in the superclass public Animal(String name) { this.name = name; } public void display() { System.out.println("Animal Name: " + name); } } class Dog extends Animal { int age; // Constructor in the subclass public Dog(String name, int age) { super(name); // Calls the superclass constructor this.age = age; } public void display() { super.display(); System.out.println("Dog's Age: " + age); } } public class Main { public static void main(String[] args) { Dog dog = new Dog("Candy", 3); dog.display(); } } //Output Animal Name: Candy Dog's Age: 3 |
Notes
this()
is used to call another constructor in the same class.super()
is used to call a constructor from the superclass.- Constructor chaining helps in code reusability and reduces redundancy.
- Reduces redundancy: Can reuse logic across different constructors.
- Cleaner code: Avoids repeating the same code in multiple constructors.
- Improves code maintenance: Easier to update code since common logic is centralized.