In this tutorial, we will learn about how to call one constructor from another constructor. In Java, you can call one constructor from another within a class using the this keyword. The this keyword is used to refer to the current object and is used to call the current class's constructors.
Here is an example of calling one constructor from another within a class.
class MyClass { int x; int y; // constructor 1 MyClass() { this(0, 0); } // constructor 2 MyClass(int x) { this(x, 0); } // constructor 3 MyClass(int x, int y) { this.x = x; this.y = y; } }
Here is an example of how you can use these constructors to create objects.
MyClass obj1 = new MyClass(); MyClass obj2 = new MyClass(5); MyClass obj3 = new MyClass(5, 10);
In this example, the MyClass class has three constructors. The first constructor, MyClass(), calls the second constructor, MyClass(int x), using the this keyword and passing in the value 0 for the x parameter. The second constructor, MyClass(int x), then calls the third constructor, MyClass(int x, int y), using the this keyword and passing in the value of the x parameter and the value 0 for the y parameter. The third constructor is the one that assigns the values passed to the object's x and y.
The first constructor call will create an object with x and y as 0, the second constructor call will create an object with x as 5 and y as 0, and the third constructor call will create an object with x as 5 and y as 10.