record にメソッドを追加
出力はどれか。
public class Main {
public static void main(String[] args) {
Item a = new Item("pen", 100);
Item b = a.withPrice(120);
System.out.println(a.price() + " " + b.price() + " " + Item.count());
}
}
record Item(String name, int price) {
static int created = 0;
Item {
created++;
}
Item withPrice(int p) {
return new Item(name, p);
}
static int count() {
return created;
}
}
- A
100 120 2 - B
120 120 2 - C
100 120 1 - D コンパイルエラーになる
正解と解説を見る
正解: A
- A: a は元の 100、withPrice で作った b は 120、コンパクトコンストラクタが2回実行されて created は 2 です。
- B: withPrice は新しい record を作るので、a の price は変わりません。
- C: withPrice の中でも new するので、コンパクトコンストラクタは2回実行されます。
- D: record にも static 変数やメソッドを追加できます。
ポイント
- record にもメソッドや static 変数を追加できます。withPrice は新しい record を作るので、a は変わりません。