Given:

class CD {

    int r;

    CD(int r) {
        this.r = r;

    }
}

class DVD extends CD {

    int c;

    DVD(int r, int c) {
        // line n1
    }
}

And given the code fragment:

DVD dvd = new DVD(10, 20);

Which code fragment should you use at line n1 to instantiate the dvd object successfully?

A.

super.r = r;
this.c = c;
B.
super(r);
this(c);
C.
super(r);
this.c = c;
D.
this.c = r;
super(c);

題解

由於第 15 行的 DVD 類別之建構子原先並沒有使用 super 或是 this 敘述來呼叫別的建構子,因此 Java 會在編譯的時候將它改成:

DVD(int r, int c) {
    super();
}

因為 CD 類別並不存在「CD()」這樣的建構子,如此一來便會造成編譯錯誤,因此需要插入一些程式至 line n1 來解決這個問題。

選項 A 並沒有使用 super 或是 this 敘述來呼叫別的建構子,無法解決問題。

選項 B 用來呼叫自身其它建構子的 this 敘述會發生錯誤,因為不是在建構子的第一行呼叫。

選項 C 正確。

選項 D 用來呼叫自身父類別建構子的 super 敘述會發生錯誤,因為不是在建構子的第一行呼叫。