static な private メソッド
出力はどれか。
public class Main {
public static void main(String[] args) {
System.out.println(Calc.twice(3) + Calc.square(3));
}
}
interface Calc {
static int twice(int n) { return times(n, 2); }
static int square(int n) { return times(n, n); }
private static int times(int a, int b) { return a * b; }
}
- A
15 - B
69 - C コンパイルエラーになる
- D 実行時に例外が発生する
正解と解説を見る
正解: A
- A: twice(3) は 6、square(3) は 9 で、int 同士の + なので足し算になり 15 です。
- B: println の引数は int + int なので数値の足し算です。文字列の連結にはならないので 69 ではありません。
- C: static メソッドの中から private static メソッドを呼ぶことはできるので、コンパイルできます。
- D: 例外になる処理はありません。
ポイント
- private static メソッドも書けます。static メソッドの共通処理をまとめられます。
twice(3)は 6、square(3)は 9 で、int 同士の足し算なので 15 です。
「デフォルト・メソッドとプライベート・メソッドの使用」をこのサイトで解く (記録・間違えた問題の解き直し・AI教師への質問)