Gau*_*tam 0 java inheritance constructor subclass superclass
在创建java程序时我遇到了问题,
子类构造函数通过调用Superclass的方法抛出Error
代码类似于:
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 ;
}
}
Run Code Online (Sandbox Code Playgroud)
错误是这样的:
$ 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
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
超类没有默认构造函数.所以你需要将适当的构造函数参数传递给超类:
super(id);
Run Code Online (Sandbox Code Playgroud)
(将这个作为双方的顶线Manager和Engineer构造器.)您也应该删除this.emp_id = id线,在这两种情况下.
通常,如果构造函数不以super(...)or或this(...)语句开头(并且您只能使用其中一个,而不是两者),则默认使用super()(不带参数).