call one constructor from another
The constructors can be overloaded to provide multiple ways to create objects of a class. To avoid code duplication and ensure consistent initialization, you can call one constructor from another within the same class using the ‘this’ keyword.
Table of Contents
Using ‘this’ to Call Another Constructor
The ‘this’ keyword is used to call another constructor in the same class. This is called constructor chaining. When using this to call another constructor, it must be the first statement in the constructor.
class Example {
int a;
int b;
// Constructor 1
Example() {
this(0, 0); // Calling Constructor 2
System.out.println("Default constructor called");
}
// Constructor 2
Example(int a, int b) {
this.a = a;
this.b = b;
System.out.println("Parameterized constructor called with values: " + a + ", " + b);
}
}
Example
Consider a class Car that can be initialized with different levels of detail:
class Car {
String make;
String model;
int year;
// Default constructor
Car() {
this("Unknown", "Unknown", 0); // Calling the parameterized constructor
System.out.println("Default constructor called");
}
// Constructor with make and model
Car(String make, String model) {
this(make, model, 2024); // Calling another parameterized constructor
System.out.println("Constructor with make and model called");
}
// Constructor with make, model, and year
Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
System.out.println("Parameterized constructor called with make: " + make + ", model: " + model + ", year: " + year);
}
void displayInfo() {
System.out.println("Car Info: " + make + " " + model + " " + year);
}
}
public class CarShowroom {
public static void main(String[] args) {
Car car1 = new Car(); // Calls default constructor
Car car2 = new Car("Toyota", "Camry"); // Calls constructor with make and model
Car car3 = new Car("Ford", "Mustang", 1967); // Calls constructor with make, model, and year
car1.displayInfo();
car2.displayInfo();
car3.displayInfo();
}
}
Key Points
- Constructor Chaining: Use this to call another constructor from within a constructor.
- First Statement: The call to another constructor must be the first statement in the constructor.
- Code Reusability: This technique helps to reuse code and maintain consistent initialization.
From this example, the ‘Car’ class has three constructors. The default constructor calls the parameterized constructor with default values, the constructor with make and model calls the fully parameterized constructor with a default year, and the fully parameterized constructor initializes all fields. This demonstrates how constructor chaining can simplify object initialization and ensure consistent behavior.