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)。
