我正在研究一个从另一个类继承的类,但是我收到一个编译器错误,提示“找不到符号构造函数Account()”。基本上我想做的是制作一个从Account扩展的InvestmentAccount类-Account的目的是通过提款/存款的方法来保持余额,InvestmentAccount与此类似,但是余额存储在股票中,而股票价格决定了如何给定一定数量的资金,许多股票将被存入或提取。以下是子类InvestmentAccount的前几行(编译器指出问题的位置):
public class InvestmentAccount extends Account
{
protected int sharePrice;
protected int numShares;
private Person customer;
public InvestmentAccount(Person customer, int sharePrice)
{
this.customer = customer;
sharePrice = sharePrice;
}
// etc...
Person类保存在另一个文件(Person.java)中。现在,这是父类(super class)帐户的前几行:
public class Account
{
private Person customer;
protected int balanceInPence;
public Account(Person customer)
{
this.customer = customer;
balanceInPence = 0;
}
// etc...
有什么原因为什么编译器不只是从Account类读取Account的符号构造函数?还是我需要在InvestmentAccount中为Account定义一个新的构造函数,告诉它继承所有内容?
谢谢
最佳答案
在super(customer)
的构造函数中使用InvestmentAccount
。
Java不知道如何只调用构造函数Account
来调用,因为它不是空的构造函数。仅当基类具有空构造函数时,才可以省略super()
。
改变
public InvestmentAccount(Person customer, int sharePrice)
{
this.customer = customer;
sharePrice = sharePrice;
}
至
public InvestmentAccount(Person customer, int sharePrice)
{
super(customer);
sharePrice = sharePrice;
}
那可行。