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行的地方出问题了~~
    谁帮我讲讲为什么呢???

解决方案 »

  1.   

    因为Employee类的父类Person类没有无参数的构造方法,
    所以在Employee类的构造方法里要显式的调用其父类的构造方法Person(String name);
    如果Person类有无参数的构造方法,则可以编译通过。
      

  2.   

    小弟初学者,好像子类的构造函数首先要调用父类的空的构造函数,然后才是执行子类的构造函数,在父类person中加个空的构造函数就没错了。不知道我说的正确不,希望高手指正!
      

  3.   

    如果你不写Person类的构造方法,
    则当你构造它的子类的时候子类会调用父类的默认构造方法
    但是你已经写了父类的构造方法
    那么当构造子类的时候它就会调用父类已写的构造方法
    由于你写的父类的构造方法有参数 而你没给它传参数
    所以它就报18行的错误
      

  4.   


    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;
    }.