問題一覧に戻る
中級オブジェクト指向
問題60: 不変オブジェクト
finalキーワードを使用してフィールドを不変にすることで、一度初期化された後は値を変更できないオブジェクトを作成できます。スレッドセーフで予測可能な動作を実現します。
public class ImmutablePoint {
// // 不変フィールド
private int x;
private int y;
public ImmutablePoint(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() { return x; }
public int getY() { return y; }
public static void main(String[] args) {
ImmutablePoint p = new ImmutablePoint(3, 4);
System.out.println("(" + p.getX() + ", " + p.getY() + ")");
}
}