Java supports method overloading. This means you can define methods with the same name but different signatures, and the compiler will work out which method to call. This process is known as overloading resolution. If you overload the constructor of a class, you can use the this
keyword in the body of one constructor to invoke another constructor.
For example, here is a class that represents a person. Each instance of the class has private name
and age
properties. The class has two overloaded constructors: Person(String)
and Person(String, int)
. The latter uses the this
keyword to call the former.
import java.util.Objects;
public class Person {
private final String name;
private int age = 0;
public Person(String name) {
this.name = Objects.requireNonNull(name);
}
public Person(String name, int age) {
this(name);
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
// Calling the `Person(String)` constructor.
var jane = new Person("Jane");
System.out.println(jane.name + " is " + jane.age + " years old.");
// Calling the `Person(String, int)` constructor.
var john = new Person("John", 3);
System.out.println(john.name + " is " + john.age + " years old.");
}
}
The Person(String)
constructor sets the name
property only. The age
property is already set to a default value by the field initializer at the top of the class.
The Person(String, int)
constructor sets both properties. It uses the this
keyword to call the Person(String)
constructor, then it sets the age
property separately. This is useful because the logic for initializing the name
property is centralized within one constructor, and the other constructor can reuse it.
Note that if you use the this
keyword in this manner, it must be the first statement in the body of a constructor.