Given:



class Vehicle {

    int x;

    Vehicle() {
        this(10); // line n1
    }

    Vehicle(int x) {
        this.x = x;
    }
}

class Car extends Vehicle {

    int y;

    Car() {
        super();
        this(20); // line n2
    }

    Car(int y) {
        this.y = y;
    }

    public String toString() {
        return super.x + ":" + this.y;
    }
}

And given the code fragment:

Vehicle y = new Car();
System.out.println(y);

What is the result?

A.

10:20

B.

0:20

C. Compilation fails at line n1
D. Compilation fails at line n2

題解

第6行(line n1)用「this」敘述呼叫了Vehicle物件的另一個建構子,而Vehicle物件的確擁有「Vehicle(int x)」建構子,因此這是沒問題的。

第20行(line n2)也用「this」敘述呼叫了Vehicle物件的另一個建構子,但並非在建構子的第1行使用「this」敘述,而會造成編譯錯誤。