同じクラスの別インスタンスの private
出力はどれか。
public class Main {
public static void main(String[] args) {
Wallet a = new Wallet(100);
Wallet b = new Wallet(50);
a.takeAll(b);
System.out.println(a.total() + " " + b.total());
}
}
class Wallet {
private int money;
Wallet(int money) { this.money = money; }
void takeAll(Wallet other) {
money += other.money;
other.money = 0;
}
int total() { return money; }
}
- A
150 0 - B
100 50 - C コンパイルエラーになる
- D 実行時に例外が発生する
正解と解説を見る
正解: A
- A: private は同じクラスの中なら別のインスタンスでも使えるので、a に 50 が移って 150、b は 0 です。
- B: takeAll で b の money が a に移されます。
- C: 同じクラスの中なので、other.money (private) にアクセスできます。
- D: 正しいコードなので例外にはなりません。
ポイント
- private は「同じインスタンスの中だけ」ではなく 同じクラスの中 なら使えます。別のインスタンスの private でも触れます。