Given:
class Sports {
int num_players;
String name, ground_condition;
Sports(int np, String sname, String sground) {
num_players = np;
name = sname;
ground_condition = sground;
}
}
class Cricket extends Sports {
int num_umpires;
int num_substitutes;
//insert code here
}
Which code fragment can be inserted at line "//insert code here" to enable the code to compile?
A.
Cricket() {
super(11, "Cricket", "Condidtion OK");
num_umpires = 3;
num_substitutes= 2;
}
B.
Cricket() {
super.ground_condition = "Condition OK";
super.name= "Cricket";
super.num_players = 11;
num_umpires = 3;
num_substitutes= 2;
}
C.
Cricket() {
this(3,2);
super(11, "Cricket", "Condidtion OK");
}
Cricket(int nu, int ns) {
this.num_umpires = nu;
this.num_substitutes= ns;
}
D.
Cricket() {
this.num_umpires = 3;
this.num_substitutes = 2;
super(11, "Cricket", "Condidtion OK");
}
题解
这题是考构造器的观念。每个类别都至少拥有一个构造器,若类别并没有实作构造器,则其在编译时还是会预设加入一段构造器程序。以题目「Cricket」这个类别为例,一开始并没有实作构造器,所以编译器会自动加入以下这段程序:
Cricket(){}
再来,所有的构造器在运行的时候都会最先调用父类别的构造器或是自己类别其他的构造器。如果构造器内并没有指定要先调用哪个构造器,那么编译器会一律在构造器的第一进程式加上「super();」叙述。以题目「Cricket」这个类别为例,调整构造器之后会变成下面这个样子:
class Cricket extends Sports {
int num_umpires;
int num_substitutes;
Cricket(){
super();
}
}
由于 Cricket 的父类别「Sports」,并没有「Sports()」这个构造器,因此原本的程序会编译失败。所以这题目要求替 Cricket 类别加上正确的构造器,使得程序能够成功编译。
选项 A 在新的构造器内的第一行加上「super(11, "Cricket", "Condidtion OK");」,调用原本就存在于 Sports 类别的「Sports(int np, String sname, String sground)」构造器,因此加上这段程序可以使程序编译成功。
选项 B 的新构造器并没有在第一行使用「super」或是「this」叙述,编译器会自动加上「super();」,但是 Sports 类别并没有「Sports()」这个构造器,因此一样会编译失败。
选项 C 的新构造器内虽然有加入「super(11, "Cricket", "Condidtion OK");」,但它放在第二行,因此会编译错误。要用「super」调用父类别的构造器,只能在构造器的第一行使用。
选项 D 编译错误的理由和选项 C 一样。
