super(...) で親のコンストラクタを選ぶ
出力はどれか。
public class Main {
public static void main(String[] args) {
Car c = new Car("red");
System.out.println(c.wheels + " " + c.color);
}
}
class Vehicle {
int wheels;
Vehicle(int wheels) { this.wheels = wheels; }
}
class Car extends Vehicle {
String color;
Car(String color) {
super(4);
this.color = color;
}
}
- A
4 red - B
0 red - C
4 null - D コンパイルエラーになる
正解と解説を見る
正解: A
- A: Car("red") は super(4) で wheels に 4 を入れてから color を設定するので、4 red になります。
- B: super(4) で親のコンストラクタが wheels = 4 を設定しているので、0 ではありません。
- C: this.color = color で "red" を入れているので、null ではありません。
- D: super(4) はコンストラクタの先頭にあり、Vehicle(int) と一致するのでコンパイルできます。
ポイント
super(引数)で親クラスのコンストラクタを選んで呼べます。コンストラクタの最初の文に書きます。