我在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++;
}
}
Run Code Online (Sandbox Code Playgroud)
AccountStudent.java - 错误:找不到符号:构造函数Account()
public class AccountStudent extends Account{
}
Run Code Online (Sandbox Code Playgroud)
修复问题 - 添加空帐户构造函数:
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我要创建空构造函数Account,因为他已经存在,因为他继承了Object类?
谢谢
为什么我要创建空构造函数Account,因为他已经存在,因为他继承了Object类?
构造函数不是继承的.如果一个类没有显式的构造函数,那么hte编译器会默默地添加一个无参数的默认构造函数,除了调用超类的无参数构造函数之外什么都不做.在你的情况下,AccountStudent因为Account没有无参数构造函数而失败.添加它是解决此问题的一种方法.另一种方法是添加一个构造函数来AccountStudent调用现有的构造函数Account,如下所示:
public class AccountStudent extends Account{
public AccountStudent(String owner){
super(owner);
}
}
Run Code Online (Sandbox Code Playgroud)