Java中子类的构造函数

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没有无参数构造函数,因此失败.

你可以解决它

通常,编译器也会隐式添加no-arg构造函数.正如Binyamin Sharet在评论中指出的那样,只有在根本没有指定构造函数的情况下才会出现这种情况.在您的情况下,您指定Person构造函数,因此不会创建隐式构造函数.