How can constructor chaining be done using this keyword In Java?
In Java, constructor chaining refers to the practice of calling one constructor from another constructor within the same class or from a superclass. This can be achieved using the this
keyword. When you use this()
in a constructor, it allows you to call another constructor in the same class.
Here’s how you can implement constructor chaining using the this
keyword:
class Example {
private int a;
private int b;
// First constructor
public Example() {
this(0, 0); // Calls the second constructor with default values
System.out.println("Default constructor called");
}
// Second constructor
public Example(int a) {
this(a, 0); // Calls the third constructor with a and default value for b
System.out.println("Constructor with one parameter called");
}
// Third constructor
public Example(int a, int b) {
this.a = a;
this.b = b; // Initializes the instance variables
System.out.println("Constructor with two parameters called");
}
public void display() {
System.out.println("a: " + a + ", b: " + b);
}
public static void main(String[] args) {
Example obj1 = new Example(); // Calls the default constructor
obj1.display();
Example obj2 = new Example(5); // Calls the constructor with one parameter
obj2.display();
Example obj3 = new Example(5, 10); // Calls the constructor with two parameters
obj3.display();
}
}
Default Constructor: The first constructor (Example()
) calls the second constructor (Example(int a, int b)
) with default values (0, 0). This is done using this(0, 0)
.
Single Parameter Constructor: The second constructor (Example(int a)
) calls the third constructor (Example(int a, int b)
) with the value of a
and a default value for b
(0). This is done using this(a, 0)
.
Two Parameters Constructor: The third constructor initializes the instance variables a
and b
.
Display Method: The display()
method is used to print the values of a
and b
.
Main Method: In the main
method, different constructors are called to demonstrate constructor chaining.
this()
in a constructor.this()
must be the first statement in the constructor.