11. class Person {
12. String name = "No name";
13. public Person(String nm) { name = nm; }
14. }
15.
16. class Employee extends Person {
17. String empID = "0000";
18. public Employee(String id) { empID = id; }
19. }
20.
21. public class EmployeeTest {
22. public static void main(String[] args) {
23. Employee e = new Employee("4321");
24. System.out.println(e.empID);
25. }
26. }
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.
Answer: D我编译了一下~~显示的结果也是18行的地方出问题了~~
谁帮我讲讲为什么呢???
12. String name = "No name";
13. public Person(String nm) { name = nm; }
14. }
15.
16. class Employee extends Person {
17. String empID = "0000";
18. public Employee(String id) { empID = id; }
19. }
20.
21. public class EmployeeTest {
22. public static void main(String[] args) {
23. Employee e = new Employee("4321");
24. System.out.println(e.empID);
25. }
26. }
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.
Answer: D我编译了一下~~显示的结果也是18行的地方出问题了~~
谁帮我讲讲为什么呢???
所以在Employee类的构造方法里要显式的调用其父类的构造方法Person(String name);
如果Person类有无参数的构造方法,则可以编译通过。
则当你构造它的子类的时候子类会调用父类的默认构造方法
但是你已经写了父类的构造方法
那么当构造子类的时候它就会调用父类已写的构造方法
由于你写的父类的构造方法有参数 而你没给它传参数
所以它就报18行的错误
class Person {
String name = "No name";
//解决方法一:public Person(){}
public Person(String nm) {
name = nm;
}
}class Employee extends Person {
String empID = "0000";
// 解决方法二:
Employee(String nm, String id) {
super(nm);
empID = id;
}
}public class EmployeeTest {
public static void main(String[] args) {
Employee e = new Employee("4321");
System.out.println(e.empID);
}
}
因为你的Person没有无参构造器,你的Employee的构造器Employee(String id)是默认调用了父类的无参构造器,而父类没有这个,所以会报错!!
解决方法:
第一种.为Person添加无参构造器.
第二种.在Employee构造器里声明你的调用父类的有参构造器
Employee(String nm, String id) {
super(nm);
empID = id;
}.