Given:

class X {

    int x1, x2, x3;
}

class Y extends X {

    int y1;

    Y() {
        x1 = 1;
        x2 = 2;
        y1 = 10;
    }
}

class Z extends Y {

    int z1;

    Z() {
        x1 = 3;
        y1 = 20;
        z1 = 100;
    }
}

public class Test3 {

    public static void main(String[] args) {
        Z obj = new Z();
        System.out.println(obj.x3 + ", " + obj.y1 + ", " + obj.z1);
    }
}

Which constructor initializes the variable x3?

A. Only the default constructor of class X
B. Only the no-argument constructor of class Y
C. Only the no-argument constructor of class Z
D. Only the default constructor of object class

題解

程式第 31 行實體化出 Z 物件,並把實體化出來的物件參考給變數 obj 儲存。在實體化 Z 物件的時候,會先執行第 21 行 Z 類別的建構子,由於這個建構子並沒有使用「super」或是「this」來指定要先呼叫哪個建構子,因此預設會在編譯時添加「super();」至第一行中。Z 類別的父類別是 Y 類別,因此 Z 類別建構子呼叫「super()」會執行第 10 行 Y 類別的建構子。基於同樣的原因,Y 類別的建構子也會去呼叫 X 類別的建構子,X 類別沒有撰寫建構子,所以在編譯時期會自動加入預設的 X 類別之建構子:

X(){
    super();
}

在這個實體化出 Z 物件的過程中,並沒有在執行建構子的時候去初始化 x3 變數的值,x3 整數變數在被宣告出來的時候,就會預設為 0,因此這題描述比較合理的是選項 A。