How do I call one constructor from another in Java?
To call one constructor from another in Java, you can use the this
keyword. Here is an example:
public class MyClass {
private int x;
private int y;
public MyClass() {
// Default constructor
this(0, 0);
}
public MyClass(int x, int y) {
// Constructor with arguments
this.x = x;
this.y = y;
}
}
In this example, the default constructor (which takes no arguments) calls the constructor with arguments (which takes two int
values) using the this
keyword. This is useful if you want to have multiple constructors with different parameter lists, but you want to share some common initialization code.
Note that you can only use the this
keyword to call another constructor from within a constructor. It is not possible to use it to call a constructor from any other method.
I hope this helps! Let me know if you have any questions.