2009-02-04 48 views
10

我正在从另一个类继承的类,但我得到一个编译器错误说:“找不到符号构造函数Account()”。基本上我想要做的是创建一个从账户账户延伸的InvestmentAccount类,旨在与提取/存款的方法保持平衡,InvestmentAccount类似,但余额存储在股票中,股票价格决定了如何许多股票是以特定金额存入或提取的。以下是前几行(约编译器在其中指出的问题)子类InvestmentAccount的:继承在Java中 - “无法找到符号构造函数”

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类阅读的符号构造的帐户?还是我需要为InvestmentAccount中的Account定义一个新的构造函数,它告诉它继承一切?

感谢

回答

25

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

,将工作。

+0

正如我规则,我总是把super()调用放在我的构造函数中,当适用时。 – eljenso 2009-02-04 10:41:56

1

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

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

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

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

1

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

+0

不是“应该”,而是“必须”。 – Bombe 2009-02-04 11:15:38

1

无论是在Account类定义默认构造函数:

public Account() {} 

还是在InvestmentAccount构造函数中调用super(customer)

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