在创建Java程序时,我遇到了一个问题,
子类构造函数通过调用超类的方法抛出错误
代码类似于以下内容:
class Manage { public static void main(String[] args) { Manager m1 = new Manager ( 35 ); } } class Employee { int emp_id; public Employee(int id) { this.emp_id = id; } public int get_id() { return emp_id; } } class Manager extends Employee { public Manager(int id ) { this.emp_id = id ; } } class Engineer extends Employee { public Engineer(int id) { this.emp_id = id ; } }
错误是这样的:
$ javac app.java app.java:25: cannot find symbol symbol : constructor Employee() location: class Employee { ^ app.java:33: cannot find symbol symbol : constructor Employee() location: class Employee { ^ 2 errors
为什么会这样?
超类没有默认的构造函数。因此,您需要将适当的构造函数参数传递给超类:
super(id);
(在Manager和Engineer构造函数中,将其作为第一行。)this.emp_id = id在两种情况下,您都应删除该行。
Manager
Engineer
this.emp_id = id
通常,如果构造函数不是以super(...)or this(...)语句开头(并且您只能使用其中之一,而不能同时使用两者),则默认情况下使用super()(不带参数)。
super(...)
this(...)
super()