2014-01-15 53 views
0

为什么我在雇员构造函数的开始找不到符号 构造函数Person?如何通过子类调用超类的参数化构造函数?

class Person { 
    String name = "noname"; 

    Person(String nm) { 
     name = nm; 
    } 
} 

class Employee extends Person { 
    String empID = "0000"; 

    Employee(String eid) {// error 
     empID = eid; 
    } 
} 

public class EmployeeTest { 
    public static void main(String args[]) { 
     Employee e1 = new Employee("4321"); 
     System.out.println(e1.empID); 
    } 
} 
+0

的'super'关键字是你的朋友。 http://docs.oracle.com/javase/tutorial/java/IandI/super.html – user2336315

回答

5

你需要调用

super(name); 

为constuctor Employee因为编译器的第一个语句,否则将隐式调用无参数的构造函数Person其犯规存在

其中name是对Employee增加了一个参数

Employee(String eid, String name) { 
    super(name); 
    empID = eid; 
} 

查看示例8.2-1 from the JLS,其中显示了如果没有明确的super方法调用,类似的示例失败。

+1

如果“员工身份证”与该人的姓名不同,这将不是正确的做法。这意味着,这个答案是可能的(但不一定)是错的。 –

+0

好的,点了,有纠正后:) – Reimeus

2

当你创建一个员工时,你需要指定一个名字和一个员工ID--因为每个员工都是一个人,每个人都需要一个名字。 Employee的构造函数应该看起来像这样。

public Employee(String eid, String name) { 
    super(name); 
    empID=eid; 
} 

该行指定如何调用超类的构造函数。它需要在那里,因为没有参数的超类没有构造函数。必须调用超类的构造函数,只有一个可用的构造函数,并且该构造函数需要指定name参数。

1

你应该做这样的事情让你的程序的工作:

class Person { 
    String name = "noname"; 
    Person(String name) { 
     this.name = name; 
    } 
} 

class Employee extends Person { 
    String empID = "0000"; 

    Employee(String empID , String name) { 
     super(name); 
     this.empID = empID; 
    } 
} 

public class EmployeeTest { 
    public static void main(String args[]) { 
     Employee e1 = new Employee("4321" , "Ramesh"); 
     System.out.println(e1.empID); 
     System.out.println(e1.name); 
    } 
} 

我有几个点的补充。

  1. 使数据成员private始终是一个好习惯。如果你想访问课堂以外的成员,请使用getters和setter。 (getName()setName()等)

  2. 你的构造函数(Person()Employee())必须被定义,如果你要在不使用参数的构造函数创建一个对象。如果您想使用非参数化构造函数实例化,则不会提供默认contstructor。所以每当你使用一个参数的构造函数是一个很好的习惯,这样做:

    class Person { 
        private String name = "noname"; 
        Person() {} 
        Person(String name) { 
         this.name = name; 
        } 
        public String getName() { 
         return this.name; 
        } 
        public void setName(String name) { 
         this.name = name; 
        } 
    } 
    
    
    class Employee extends Person { 
        private String empID = "0000"; 
        Employee() {} 
        Employee(String empID,String name) { 
         this.empID = empID; 
        } 
        public String getEmpID() { 
         return this.empID; 
        } 
        public void setName(String empID) { 
         this.empID = empID; 
        } 
    } 
    
相关问题