onl*_*man 4 java constructor superclass
在编译这个程序时,我得到错误 -
class Person {
Person(int a) { }
}
class Employee extends Person {
Employee(int b) { }
}
public class A1{
public static void main(String[] args){ }
}
Run Code Online (Sandbox Code Playgroud)
错误 - 找不到构造函数Person().为什么定义Person()是必要的?
aio*_*obe 25
创建一个Employee你同时创建一个Person.为了确保Person正确构造,编译器super()在Employee构造函数中添加了一个隐式调用:
class Employee extends Person {
Employee(int id) {
super(); // implicitly added by the compiler.
}
}
Run Code Online (Sandbox Code Playgroud)
由于Person没有无参数构造函数,因此失败.
你可以解决它
添加对super的显式调用,如下所示:
class Employee extends Person {
Employee(int id) {
super(id);
}
}
Run Code Online (Sandbox Code Playgroud)或者通过添加no-arg构造函数Person:
class Person {
Person() {
}
Person(int a) {
}
}
Run Code Online (Sandbox Code Playgroud)通常,编译器也会隐式添加no-arg构造函数.正如Binyamin Sharet在评论中指出的那样,只有在根本没有指定构造函数的情况下才会出现这种情况.在您的情况下,您已指定Person构造函数,因此不会创建隐式构造函数.
| 归档时间: |
|
| 查看次数: |
39017 次 |
| 最近记录: |