2009-02-04 83 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; 
    } 
}