this() による自クラスコンストラクタ呼び出しの例です。
class Student {
String name;
int age;
// 引数付きコンストラクタ
Student(String name, int age) {
this.name = name; // thisで自インスタンスのフィールドを参照
this.age = age;
}
// 引数なしコンストラクタ (thisで別のコンストラクタを呼び出す)
Student() {
this("未定", 18); // 必ずコンストラクタの先頭行に記述
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("太郎", 20);
Student s2 = new Student(); // 未定, 18
}
}