编译此程序时,我收到错误 -
class Person {
Person(int a) { }
}
class Employee extends Person {
Employee(int b) { }
}
public class A1{
public static void main(String[] args){ }
}
错误 - 找不到构造函数Person()。 为什么定义Person()是必要的?
答案 0 :(得分:25)
创建Employee
时,您正在同时创建Person
。为了确保正确构造Person
,编译器在super()
构造函数中添加了对Employee
的隐式调用:
class Employee extends Person {
Employee(int id) {
super(); // implicitly added by the compiler.
}
}
由于Person
没有无参数构造函数,因此失败。
你可以通过
来解决它添加对super的显式调用,如下所示:
class Employee extends Person {
Employee(int id) {
super(id);
}
}
或向Person
添加无参数构造函数:
class Person {
Person() {
}
Person(int a) {
}
}
通常编译器也会隐式添加no-arg构造函数。正如Binyamin Sharet在评论中指出的那样,只有在没有指定构造函数的情况下才会出现这种情况。在你的情况下,你已经指定了一个Person构造函数,因此没有创建隐式构造函数。
答案 1 :(得分:2)
Employee
的构造函数不知道如何构造超类Person
。如果没有明确告诉它,它将默认尝试超类的no-args构造函数,它不存在。因此错误。
修复方法是:
class Employee extends person {
public Employee(int id) {
super(id);
}
}
答案 2 :(得分:1)
Java实际上将此代码视为:
class Person {
Person(int nm) { }
}
class Employee extends Person {
Employee(int id) {
super();
}
}
public class EmployeeTest1 {
public static void main(String[] args){ }
}
由于没有Person()构造函数,因此失败。而是尝试:
class Person {
Person(int nm) { }
}
class Employee extends Person {
Employee(int id) {
super(id);
}
}
public class EmployeeTest1 {
public static void main(String[] args){ }
}
答案 3 :(得分:1)
Java为您提供了一个不带参数的默认构造函数。构造函数也没有正文,所以它是这样的:public Person() {}
。在您定义自己的构造函数的那一刻,您的构造函数将取代默认构造函数,因此在您的情况下,Person(int nm){}
取代Person() { }
。您的调用正试图隐式调用Person() { }
,并且由于此构造函数不再存在,因此代码失败。请查看this之前的SO问题以获取更多信息。
答案 4 :(得分:1)
以上回答是正确的,还有一些补充:你可以直接调用super(int n)来避免在这里隐式添加super():
class Employee extends Person {
Employee(int id) { super(int id);}
}
PS:对不起我的写作。英语不是我的母语。
答案 5 :(得分:0)
这不是100%与您的问题有关。但这也与java构造函数有关。假设您的Person类没有默认构造函数,并且构造函数参数不是原始数据类型。它们是对象。
但是,如果要使用默认构造函数创建子类,请采用以下解决方案。 请记住,您不允许更改超类。
我创建了另一个名为contact的类。
class Contact{
private String name;
private int number;
public Contact(String name, int number) {
this.name = name;
this.number = number;
}
}
然后是代码。
//Super Class - "Can't change the code"
class Person {
Person(Contact contact) { }
}
//Sub Class
class Employee extends Person {
private static Contact c;
static {
c = new Contact("Anna",10);
}
Employee() {
super(c);
}
}
您必须为Contact类的静态变量保留要传递给超类构造函数的对象实例。