コンストラクタ: オブジェクト初期化

new 時に呼ばれる。検証と初期化を行う。

コンストラクタ
new 時に呼ばれる初期化メソッド。
this()
同じクラスの他コンストラクタを呼ぶ。
super()
親クラスのコンストラクタを呼ぶ。
Factory Line

コンストラクタは「工場の組み立てライン」。 新品(new)が作られるとき、組み立てラインを通って初期化される。 動かない製品(不正な状態)は出荷できない。

コンストラクタ

Default, Parameterized, Copy
public class Person {
private String name;
private int age;
// デフォルトコンストラクタ
public Person() {
this.name = "Unknown";
this.age = 0;
}
// 引数付きコンストラクタ
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// コピーコンストラクタ
public Person(Person other) {
this.name = other.name;
this.age = other.age;
}
}
// 使用
Person p1 = new Person(); // デフォルト
Person p2 = new Person("Alice", 30); // 引数付き
Person p3 = new Person(p2); // コピー
実行結果
p1: Unknown, 0\np2: Alice, 30\np3: Alice, 30
Bad
// ❌ Bad: フィールドを直接公開
public class User {
public String name; // 不正な値が入り得る
}
Good
// ✅ Good: コンストラクタで検証
public class User {
private final String name;
public User(String name) {
if (name == null || name.isEmpty()) {
throw new IllegalArgumentException();
}
this.name = name;
}
}

パターン

this(), super(), Record
// this() で他のコンストラクタを呼ぶ
public class Rectangle {
private int width, height;
public Rectangle() {
this(1, 1); // 他のコンストラクタを呼ぶ
}
public Rectangle(int size) {
this(size, size); // 正方形
}
public Rectangle(int w, int h) {
this.width = w;
this.height = h;
}
}
// super() で親のコンストラクタを呼ぶ
public class Employee extends Person {
private String department;
public Employee(String name, int age, String dept) {
super(name, age); // 親のコンストラクタ
this.department = dept;
}
}
// Recordでイミュータブル (Java 16+)
public record Point(int x, int y) { }
// コンストラクタ自動生成
Tip: コンストラクタで引数を検証する。不正な状態を防ぐ。

合格ライン

コンストラクタのオーバーロードができる
this() と super() を使える

参考リンク

演習課題

課題1: オーバーロード
複数の引数パターンを持つコンストラクタを作成してください。
課題2: this() 連鎖
this() を使ってコンストラクタを連鎖させてください。

次のステップ