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

java继承问题-必须在父类中创建空构造函数,java,inheritance,Java,Inheritance,我在netbeans ubuntu java标准项目上编程(测试准备)。 当我创建AccountStudent.java时,我得到一个错误 Account.java public abstract class Account { protected double _sum; protected String _owner; protected static int accountCounter=0; public Account(String owner){ this._su

我在netbeans ubuntu java标准项目上编程(测试准备)。 当我创建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++;
 }
}
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++;
 }
}
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++;
 }
}
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++;
 }
}
如果构造函数帐户已经存在,我为什么要创建空的构造函数帐户,因为他继承了对象类?

谢谢

为什么要创建空构造函数 说明他是否已经存在,因为他 继承对象类

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

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

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

所以,即使它从对象继承,也不意味着它将有一个默认构造函数

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

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

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

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

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

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

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

如果一个类不包含构造函数声明,那么会自动提供一个不带参数的默认构造函数。 如果要声明的类是原始类对象,则默认构造函数的主体为空。 否则,默认构造函数不接受参数,只调用不带参数的超类构造函数

在这种情况下,AccountStudent类没有任何构造函数,因此编译器会为您添加一个默认构造函数,并添加对超类构造函数的调用。因此,您的子类实际上如下所示:

class AccountStudent extends Account{ AccountStudent() { super(); } } 类帐户学生扩展帐户{ 会计学生(){ 超级(); } } 扩展类的对象包含以下状态变量(字段): 继承自超类以及定义的状态变量 在课堂上的局部。构造扩展对象的步骤 类,则必须正确初始化两组状态变量。这个 扩展类的构造函数可以处理自己的状态,但只能处理 超类知道如何正确初始化其状态,以便 遵守合同。扩展类的构造函数必须委托 隐式或显式构造继承状态 调用超类构造函数

爪哇™ 程序设计语言,第四版
作者:肯·阿诺德、詹姆斯·戈斯林、大卫·霍姆斯

@Micheal:有打字错误。公共帐户(字符串所有者){super(所有者);}应该是公共帐户学生(字符串所有者){super(所有者);}。谢谢你的回答。这个问题已经有两年多的历史了,并且已经得到了回答。我们很高兴看到你在更紧迫的问题上做出了努力:)没问题,我会努力的!谢谢!:)