Constructor chaining is a fundamental Java concept that allows one constructor to call another within the same class or across a parent-child hierarchy. In this article, we break down how the this() keyword enables constructor chaining, complete with practical examples and tricky interview questions.
What Is Constructor Chaining?
Constructor chaining occurs when a constructor calls another constructor of the same class (using this()) or a superclass constructor (using super()). This technique helps avoid code duplication and ensures that initialization logic is centralized.
Using this() for Same-Class Chaining
Within a class, you can use this() to invoke another constructor. The call must be the first statement in the constructor. Here's an example:
public class Employee {
private String name;
private int id;
// No-argument constructor
public Employee() {
this("Unknown", 0); // Calls the parameterized constructor
}
// Parameterized constructor
public Employee(String name, int id) {
this.name = name;
this.id = id;
}
}
In this example, Employee() chains to Employee(String, int) to set default values.
Tricky Interview Questions
Interviewers often test your understanding of constructor chaining with questions like:
-
What happens if you don't explicitly call
this()orsuper()?
The compiler automatically insertssuper()(the no-argument constructor of the parent class) as the first statement. -
Can you use
this()andsuper()together?
No. Both must be the first statement in a constructor, so they cannot coexist. -
What is the output of the following code?
class Base {
Base() { System.out.println("Base"); }
}
class Derived extends Base {
Derived() {
this("Derived");
System.out.println("Derived no-arg");
}
Derived(String s) {
System.out.println(s);
}
}
Answer:
Base
Derived
Derived no-arg
Why? The Derived() constructor first calls this("Derived"), which triggers super() (printing "Base"), then prints "Derived", and finally returns to Derived() to print "Derived no-arg".
Best Practices
- Always keep
this()orsuper()as the first line. - Avoid deep chaining (more than 2-3 levels) for readability.
- Use chaining to reduce redundant initialization code.
Mastering constructor chaining not only helps you write cleaner Java code but also prepares you for tricky interview questions. Practice with the examples above to solidify your understanding.