10

我正在研究一个从另一个类继承的类,但我收到一个编译器错误,提示“找不到符号构造函数 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) 中。现在这里是超类 Account 的前几行:

public class Account 
{
    private Person customer;
    protected int balanceInPence;

    public Account(Person customer)
    {
        this.customer = customer;
        balanceInPence = 0;
    }
    // etc...

为什么编译器不只是从 Account 类中读取 Account 的符号构造函数?或者我是否需要在 InvestmentAccount 中为 Account 定义一个新的构造函数,告诉它继承所有内容?

谢谢

4

5 回答 5

25

super(customer)InvestmentAccounts 构造函数中使用。

Java 无法知道如何调用唯一的构造函数Account,因为它不是空的构造函数super()只有当你的基类有一个空的构造函数时,你才能省略。

改变

public InvestmentAccount(Person customer, int sharePrice)
{
        this.customer = customer;
        sharePrice = sharePrice;
}

public InvestmentAccount(Person customer, int sharePrice)
{
        super(customer);
        sharePrice = sharePrice;
}

那可行。

于 2009-02-04T10:21:38.123 回答
2

您必须调用超类构造函数,否则 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;
    }
}
于 2009-02-04T10:28:45.427 回答
1

如果基类没有默认构造函数(没有参数的构造函数),则必须显式调用基类的构造函数。

在您的情况下,构造函数应该是:

public InvestmentAccount(Person customer, int sharePrice) {
    super(customer);
    sharePrice = sharePrice;
}

并且不要重新定义customer为子类的实例变量!

于 2009-02-04T10:23:07.513 回答
1

调用 super() 方法。如果要调用 Account(Person) 构造函数,请使用语句 super(customer); 这也应该是您的 InvestmentAccount 构造函数中的第一个语句

于 2009-02-04T10:23:39.913 回答
1

在类中定义一个默认构造函数Account

public Account() {}

或者调用super(customer)构造InvestmentAccount函数。

于 2009-02-04T10:23:55.217 回答