我正在处理一个继承自另一个类的类,但我收到一个编译器错误,提示“找不到符号构造函数 Account()”。基本上我想做的是制作一个 InvestmentAccount 类,它从 Account 扩展 - 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) Account 的前几行:
public class Account
{
private Person customer;
protected int balanceInPence;
public Account(Person customer)
{
this.customer = customer;
balanceInPence = 0;
}
// etc...
编译器不只是从 Account 类中读取 Account 的符号构造函数有什么原因吗?或者我是否需要在 InvestmentAccount 中为 Account 定义一个新的构造函数,告诉它继承所有内容?
谢谢
最佳答案
在 InvestmentAccount
的构造函数中使用 super(customer)
。
Java 无法知道如何调用 Account
拥有的唯一 构造函数,因为它不是空构造函数。仅当您的基类具有空构造函数时,您才可以省略 super()
。
改变
public InvestmentAccount(Person customer, int sharePrice)
{
this.customer = customer;
sharePrice = sharePrice;
}
到
public InvestmentAccount(Person customer, int sharePrice)
{
super(customer);
sharePrice = sharePrice;
}
那会起作用。
关于java - Java 中的继承 - "Cannot find symbol constructor",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/510784/