How do I call one constructor from another in Java?

 

In Java, you can call one constructor from another within the same class using the this() keyword. This is known as constructor chaining. Here's an example:

java
public class ConstructorChainingExample { private String name; private int age; public ConstructorChainingExample() { this("John Doe"); // Calls the parameterized constructor with a default name } public ConstructorChainingExample(String name) { this(name, 30); // Calls the parameterized constructor with the given name and default age } public ConstructorChainingExample(String name, int age) { this.name = name; this.age = age; } public void displayInfo() { System.out.println("Name: " + name); System.out.println("Age: " + age); } public static void main(String[] args) { ConstructorChainingExample person1 = new ConstructorChainingExample(); person1.displayInfo(); ConstructorChainingExample person2 = new ConstructorChainingExample("Alice"); person2.displayInfo(); ConstructorChainingExample person3 = new ConstructorChainingExample("Bob", 25); person3.displayInfo(); } }

In this example, the class ConstructorChainingExample has three constructors:

  1. A default constructor that chains to the parameterized constructor with a default name.
  2. A parameterized constructor that chains to the second parameterized constructor with a default age.
  3. Another parameterized constructor that sets both the name and age.

Each constructor uses this() to call another constructor in the chain. This way, you can avoid duplicating initialization code and maintain a clear hierarchy of constructor behavior.

When you create instances of the class using different constructors, the chained constructors are invoked, and the values are set accordingly. The displayInfo() method is used to display the information of each person.

Constructor chaining is a useful technique for reusing code and creating constructors with varying levels of initialization.

Comments