Constructor Chaining in Java
Constructor chaining is the process of calling one constructor from another constructor within the same class, or from a constructor in the superclass. It's done using the this() and super() keywords.
Chaining Within the Same Class — this()
class Student {
String name;
int age;
Student() {
this("Unknown", 0);
System.out.println("Default constructor called");
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
}
Chaining to the Superclass — super()
class Person {
Person(String name) {
System.out.println("Person constructor: " + name);
}
}
class Employee extends Person {
Employee(String name) {
super(name);
System.out.println("Employee constructor");
}
}
Rules of Constructor Chaining
this()orsuper()must be the first statement in a constructor- A constructor cannot call both
this()andsuper()at the same time - If neither is written explicitly, Java inserts an implicit call to
super()
Why Use Constructor Chaining?
- Avoids duplicating initialization code across multiple constructors
- Ensures a common initialization path is always followed
- Makes it easier to maintain default values in one place
Constructor chaining within the same class must use
this(), while chaining to a parent class constructor must use super() — they can never be mixed in the same call.Master Java with Uncodemy
Hands-on training, live projects, and placement support in our Java Programming Course.