this() Statement in Java: Constructor Chaining Explained
this() Statement in Java
The this() statement in Java is used to call one constructor from another constructor within the same class.
It helps in constructor chaining inside the same class and avoids code duplication.
✅ Correct Definition
- this() is used to call the current class constructor
- It is used inside a constructor
- It must be the first statement in the constructor body
- It is written explicitly by the programmer
- It does not support recursive calls
- A constructor body must contain either this() or super(), not both
⚠️ Important Correction
- this() → calls constructor of the same class
- super() → calls constructor of the super (parent) class
🌍 Real-Life Example
Online Order System
- One constructor sets default values
- Another constructor sets custom values
- Instead of repeating code, one constructor calls another using this()
🔹 Syntax
this(parameterList);
🔹 Example of this() Statement
class Student {
Student() {
this(101, "Rahul");
System.out.println("Default Constructor");
}
Student(int id, String name) {
System.out.println("ID: " + id + ", Name: " + name);
}
public static void main(String[] args) {
Student s = new Student();
}
}
🔍 Output
ID: 101, Name: Rahul
Default Constructor
🧠 Explanation
this(101, "Rahul") calls the parameterized constructor
Code reuse is achieved
Constructor execution follows a chain
❌ Recursive Call Not Allowed
Student() {
this(); // ❌ Compile-time error
}
Reason:
Recursive constructor calls lead to infinite loop, so Java does not allow it.
📌 Important Points to Remember
- this() must be the first line in constructor
- Only one constructor call (this() or super()) is allowed
- Improves code readability
- Reduces duplicate initialization code
Comments
Post a Comment