class Person { String name = "No name"; public Person(String nm) {name = nm;} } class Employee extends Person { String empID = "0000"; public Employee(String id) {empID = id;} } class EmployeeTest { public static void main(String[] args) { Employee e = new Employee("4321"); System.out.println(e.empID); } }
What is the result?
A. 4321
B. 0000
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 18.
答案:D
解析:
由於繼承的關係
子代類別被實體化成為物件時
父代的建構子會先被運行
預設運行的父代建構子是無引數的建構子super()
但是Person 類別沒有無引數的建構子
這是就會出錯
這題要修正的話,有兩種方式:
1.在Employee的建構子的第一行加入super("name");
2.在Person類別中加入一個無引數的建構子Person(){}
0 意見:
張貼留言