[英]Inheritance in Java - “Cannot find symbol constructor”
我正在从一个继承自另一个类的类,但我收到一个编译错误,说“找不到符号构造函数Account()”。 基本上我要做的是创建一个类别的InvestmentAccount,它来自账户 - 账户是为了与取款/存款方法保持平衡,而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)中。 现在这里是超类帐户的前几行:
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将不知道您要调用哪个构造函数来在子类上构建超类。
public class InvestmentAccount extends Account {
protected int sharePrice;
protected int numShares;
private Person customer;
public InvestmentAccount(Person customer, int sharePrice) {
super(customer);
this.customer = customer;
sharePrice = sharePrice;
}
}
如果基类没有默认构造函数(没有参数的构造函数),则必须显式调用基类的构造函数。
在您的情况下,构造函数应该是:
public InvestmentAccount(Person customer, int sharePrice) {
super(customer);
sharePrice = sharePrice;
}
并且不要将customer
重新定义为子类的实例变量!
调用super()方法。 如果要调用Account(Person)构造函数,请使用语句super(customer); 这也应该是您的InvestmentAccount构造函数中的第一个参数
在Account
类中定义默认构造函数:
public Account() {}
或者在InvestmentAccount
构造函数中调用super(customer)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.