Can you call a constructor of a class inside another constructor In Java?
Yes, you can call a constructor of a class inside another constructor in Java using the this
keyword. This is known as constructor chaining. It allows one constructor to invoke another constructor within the same class, helping to reduce code duplication and improve maintainability.
A constructor is a special method in a class that is called when an object of the class is instantiated. It typically initializes the object's attributes and allocates resources. Constructors have the same name as the class and do not have a return type.
In Java, you can call one constructor from another using this(parameters)
. This must be the first statement in the constructor.
Here’s a simple example to illustrate this:
class Person {
String name;
int age;
// Constructor with two parameters
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Constructor with one parameter, calls the two-parameter constructor
public Person(String name) {
this(name, 0); // Calls the Person(name, age) constructor
}
// Default constructor, calls the one-parameter constructor
public Person() {
this("Unknown"); // Calls the Person(name) constructor
}
public void displayInfo() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person("Alice", 30);
Person person2 = new Person("Bob");
Person person3 = new Person();
person1.displayInfo(); // Output: Name: Alice, Age: 30
person2.displayInfo(); // Output: Name: Bob, Age: 0
person3.displayInfo(); // Output: Name: Unknown, Age: 0
}
}
Java includes constructors to:
In summary, constructor chaining is a useful feature in Java that promotes code reuse and clarity in object initialization.