java继承问题 - 必须在父类中创建空构造函数

时间:2010-08-17 21:53:02

标签: java inheritance

我在netbeans ubuntu java standart项目(测试准备)上编程。 当我创建AccountStudent.java时,我收到错误。

Account.java

public abstract class Account {
 protected double _sum;
 protected String _owner;
 protected static int accountCounter=0;

 public Account(String owner){
     this._sum=0;
     this._owner=owner;
     accountCounter++;
 }
}

AccountStudent.java - 错误:找不到符号:构造函数Account()

public class AccountStudent extends Account{

}

修复问题 - 添加空帐户构造函数:

Account.java

public abstract class Account {
 protected double _sum;
 protected String _owner;
 protected static int accountCounter=0;

 public Account(){

 }

 public Account(String owner){
     this._sum=0;
     this._owner=owner;
     accountCounter++;
 }
}

为什么我要创建空构造函数Account,因为他已经存在因为他继承了Object类?

由于

4 个答案:

答案 0 :(得分:8)

  

我为什么要创建空构造函数   如果因为他已经存在,请说明   继承Object类?

构造函数不是继承的。如果一个类没有显式的构造函数,那么hte编译器会默默地添加一个无参数的默认构造函数,除了调用超类的无参数构造函数之外什么都不做。在您的情况下,AccountStudent失败,因为Account没有无参数构造函数。添加它是解决此问题的一种方法。另一种方法是向AccountStudent添加一个构造函数,调用Account的现有构造函数,如下所示:

public class AccountStudent extends Account{
    public AccountStudent(String owner){
        super(owner);
    }
}

答案 1 :(得分:3)

Java中的每个类都必须有一个构造函数,如果你没有定义一个,编译器会为你做这个并创建一个默认的构造函数(没有参数的构造函数)。如果你自己创建一个构造函数,那么编译器不需要创建一个。

因此,即使它继承自Object,也不意味着它将具有默认构造函数。

实例化AccountStudent时,需要调用父构造函数。 默认情况下,如果您没有指定自己要调用的父构造函数,它将调用默认构造函数。 如果要显式调用父构造函数,则可以使用super()

有三种方法可以避免错误:

使用从子构造函数获取的参数调用父构造函数:

public class AccountStudent extends Account{
    public AccountStudent(String owner){
        super(String owner);
    }

}

使用您自己创建的参数调用父构造函数:

public class AccountStudent extends Account{
    public AccountStudent(){
        super("Student");
    }

}

调用默认的父构造函数,但是您需要创建一个,因为如果非默认构造函数已经存在,编译器将不会创建一个。 (你给出的解决方案)

答案 2 :(得分:1)

JLS 8.8.9 Default Constructor

如果类不包含构造函数声明,则会自动提供不带参数的默认构造函数。 如果声明的类是原始类Object,则默认构造函数具有空体。 否则,默认构造函数不带参数,只调用不带参数的超类构造函数。

在这种情况下,AccountStudent类没有任何构造函数,因此编译器会为您添加一个默认构造函数,并且还会添加对超类构造函数的调用。所以你的孩子班有效地看起来像:

    class AccountStudent extends Account{
      AccountStudent() {
      super();
     }
    }

答案 3 :(得分:1)

  

扩展类的对象包含状态变量(字段)   继承自超类以及定义的状态变量   在课堂上本地。构造扩展的对象   class,你必须正确初始化两组状态变量。该   扩展类的构造函数可以处理自己的状态,但只能处理   超类知道如何正确初始化其状态,以便它   合同很荣幸。扩展类的构造函数必须委托   通过隐式或显式构造继承状态   调用超类构造函数。

Java™编程语言,第四版 作者:Ken Arnold,James Gosling,David Holmes

相关问题