Java子类的构造函数 [英] constructor of subclass in Java
问题描述
编译这个程序时出现错误-
When compiling this program, I get error-
class Person {
Person(int a) { }
}
class Employee extends Person {
Employee(int b) { }
}
public class A1{
public static void main(String[] args){ }
}
错误 - 找不到构造函数 Person().为什么需要定义 Person()?
Error- Cannot find Constructor Person(). Why defining Person() is necessary?
推荐答案
在创建 Employee
时,您同时创建了一个 Person
.为了确保 Person
正确构造,编译器在 Employee
构造函数中添加了对 super()
的隐式调用:
When creating an Employee
you're creating a Person
at the same time. To make sure the Person
is properly constructed, the compiler adds an implicit call to super()
in the Employee
constructor:
class Employee extends Person {
Employee(int id) {
super(); // implicitly added by the compiler.
}
}
由于 Person
没有无参数构造函数,因此失败.
Since Person
does not have a no-argument constructor this fails.
您可以通过任一方式解决
You solve it by either
添加对 super 的显式调用,如下所示:
adding an explicit call to super, like this:
class Employee extends Person {
Employee(int id) {
super(id);
}
}
或者通过向 Person
添加一个无参数构造函数:
or by adding a no-arg constructor to Person
:
class Person {
Person() {
}
Person(int a) {
}
}
通常编译器也会隐式添加一个无参数构造函数.然而,正如 Binyamin Sharet 在评论中指出的那样,只有在根本没有指定构造函数的情况下才会出现这种情况.在您的情况下,您已经指定了一个 Person 构造函数,因此没有创建隐式构造函数.
Usually a no-arg constructor is also implicitly added by the compiler. As Binyamin Sharet points out in the comments however, this is only the case if no constructor is specified at all. In your case, you have specified a Person constructor, thus no implicit constructor is created.
这篇关于Java子类的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!