this()
is used to call another constructor within the same class.
Helps avoid code duplication when multiple constructors share logic.
Example
class Car {
String moel;
int year;
Car() {
this("Unknown", 2020); // calls second constructor
}
Car(String model, int year) {
this.model = model;
this.year = year;
}
}
Key Rules
- Must be the first statement in the constructor.
- Can only be used once per constructor.
- Cannot be used with super() in the same constructor.
Comparison
this()
vs super()
Keyword | Calls⦠| Used For |
---|---|---|
this() | Another constructor (same class) | Constructor chaining within class |
super() | Parent class constructor | Inheritance-base constructor chaining |
Tip
Use
this()
for constructor chaining when you have default values or shared logic.
Never usethis()
andsuper()
together - Java wonβt allow it.
Parent: _OOP