Java:Inherited类构造函数调用Super类 [英] Java: Inherited class constructor is calling Super class
问题描述
在创建一个java程序时遇到一个问题,
While creating a java program i encountered a problem,
子类构造函数通过调用超类的方法抛出一个错误
A subclass constructor is throwing an Error by calling the Superclass's method
代码类似于:
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
推荐答案
超类没有默认构造函数。所以你需要传递适当的构造函数参数到超类:
The superclass doesn't have a default constructor. So you need to pass the appropriate constructor arguments to the superclass:
super(id);
(将此作为经理
和 Engineer
构造函数。)在这两种情况下,还应删除 this.emp_id = id
行。
(Put this as the top line in both the Manager
and Engineer
constructors.) You should also remove the this.emp_id = id
line, in both cases.
一般来说,如果你的构造函数不以 super(...)
或 this(...)
语句(和你只能有一个,而不是两个),然后它默认使用 super()
(没有参数)。
In general, if your constructor doesn't start with a super(...)
or this(...)
statement (and you can only have one of these, not both), then it defaults to using super()
(with no arguments).
这篇关于Java:Inherited类构造函数调用Super类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!