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 叙述会发生错误,因为不是在构造器的第一行调用。
