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

B.

null 0 Auto
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」敘述,但不是在建構子的第一行呼叫,因此會編譯錯誤。