Given:
class Vehicle {
String type = "4W";
int maxSpeed = 100;
Vehicle(String type, int maxSpeed) {
this.type = type;
this.maxSpeed = maxSpeed;
}
}
class Car extends Vehicle {
String trans;
Car(String trans) { // line n1
this.trans = trans;
}
Car(String type, int maxSpeed, String trans) {
super(type, maxSpeed);
this(trans); //line n2
}
}
And given the code fragment:
public static void main(String[] args) {
Car c1 = new Car("Auto");
Car c2 = new Car("4W", 150, "Manual");
System.out.println(c1.type + " " + c1.maxSpeed + " " + c1.trans);
System.out.println(c2.type + " " + c2.maxSpeed + " " + c2.trans);
}
What is the result?
A.
4W 100 Auto
4W 150 Manual
4W 150 Manual
B.
null 0 Auto
4W 150 Manual
4W 150 Manual
C. Compilation fails only at line n1
D. Compilation fails only at line n2
E. Compilation fails at both line n1 and line n2
题解
line n1 的构造器有误,由于其并没有使用「super」或是「this」叙述来决定要先运行的构造器,因此预设会自动加入「super();」于构造器的第一行。但是 Car 所继承的 Vehicle 类别并没有「Vehicle()」这个构造器,因此会有编译错误。
line n2 使用了「this」叙述,但不是在构造器的第一行调用,因此会编译错误。
