Java中的继承 - “找不到符号构造函数”

时间:2009-02-04 10:19:36

标签: java inheritance polymorphism

我正在处理一个继承自另一个类的类,但是我收到编译错误,说“找不到符号构造函数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定义一个新的构造函数,它告诉它继承所有内容?

由于

5 个答案:

答案 0 :(得分:25)

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;
}

这将有效。

答案 1 :(得分: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;
    }
}

答案 2 :(得分:1)

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

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

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

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

答案 3 :(得分:1)

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

答案 4 :(得分:1)

Account类中定义默认构造函数:

public Account() {}

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