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。