Given the code fragment:
class Student {
int rollnumber;
String name;
List cources = new ArrayList();
// insert code here
public String toString() {
return rollnumber + " : " + name + " : " + cources;
}
}
And,
public class Test {
public static void main(String[] args) {
List cs = new ArrayList();
cs.add("Java");
cs.add("C");
Student s = new Student(123, "Fred", cs);
System.out.println(s);
}
}
Which code fragment, when inserted at line // insert code here, enables class Test to print 123 : Fred : [Java, C]?
A.
private Student(int i, String name, List cs) {
/* initialization code goes here */
}
B.
public void Student(int i, String name, List cs) {
/* initialization code goes here */
}
C.
Student(int i, String name, List cs) {
/* initialization code goes here */
}
D.
Student(int i, String name, ArrayList cs) {
/* initialization code goes here */
}
题解
题目原先的程序会在第 26 行发生编译错误,原因在于 Student 类别内并没有实作出 Student(int i, String name, List cs) 这样的构造器。因此必须要加入构造器至程序第 9 行。
选项 A,构造器若使用 private 来修饰,就无法在类别之外被实体化了。
选项 B,构造器不能撰写回传值的型态,连无回传值型态「void」都不行。
选项 C,正确答案。
选项 D,因为隐含式(implicit)的自动转型只能向上转型,因此第三个参数应该要是 List 型态或是 List 继承之父类别的对象型态(如 Collection、Iterable、Object),而不能是继承 List 的子类别(如 ArrayList、LinkedList)。
