To call one constructor from another in Java, use the this()
keyword within the constructor. This allows you to invoke another constructor in the same class, promoting code reuse and reducing redundancy. Here’s how to do it:
Key Rules:
this()
must be the first statement in the constructor.- Chaining: Constructors can call one another, but cycles (recursive calls) are invalid.
- Parameter Matching: The arguments passed to
this()
must match the parameters of the target constructor.
Example: Constructor Chaining
public class Person {
private String name;
private int age;
// Primary constructor with all parameters
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Secondary constructor (calls the primary constructor with a default age)
public Person(String name) {
this(name, 30); // Calls Person(String name, int age)
}
// Default constructor (calls the secondary constructor)
public Person() {
this("Unknown"); // Calls Person(String name)
}
}
How It Works:
Person(String name)
callsPerson(String name, int age)
withage = 30
.Person()
callsPerson(String name)
withname = "Unknown"
.
Benefits:
- Avoids code duplication: Centralizes initialization logic in one constructor.
- Maintainability: Changes to initialization only need to be made in one place.
- Flexibility: Supports multiple ways to initialize an object.
Common Use Cases:
- Default Values: Provide defaults for missing parameters.
- Validation: Centralize validation logic in a primary constructor.
- Overloading: Simplify object creation with different parameter sets.
Example: Rectangle Class
public class Rectangle {
private int width;
private int height;
// General constructor
public Rectangle(int width, int height) {
this.width = width;
this.height = height;
}
// Square constructor (calls the general constructor)
public Rectangle(int side) {
this(side, side); // Sets width = height = side
}
}
Important Notes:
super()
vs.this()
: Usesuper()
to call a superclass constructor, but it cannot coexist withthis()
in the same constructor.- Error Handling: Ensure parameter validity in the primary constructor to avoid cascading issues.