Java中的子类的构造函数 [英] constructor of subclass in Java

查看:279
本文介绍了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 被正确构造,编译器在<$ c中添加对 super() $ c> Employee 构造函数:

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.
     }
 }

Since Person does not have a no-argument constructor this fails.

您可以通过

    来解决这个问题。
  • 向super添加一个显式调用,如下所示:

  • adding an explicit call to super, like this:

 class Employee extends Person {
     Employee(int id) {
         super(id);
     }
 }


  • 人:

    class Person {
        Person() {
        }
    
        Person(int a) {
        }
    }
    

    li>

  • 通常,编译器还会隐式添加一个无参数构造函数。正如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屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆