2015-07-21 156 views
0

由於構造函數的問題,我編譯代碼時出現錯誤。Java - 繼承與構造函數錯誤

這裏是我的父類的構造函數:

public BankAccount(final String theNameOfOwner, final double theInterestRate) 
    { 
     myName = theNameOfOwner; 
     myInterestRate = theInterestRate; 
     myBalance = 0; 
     myMonthlyWithdrawCount = 0; 
     myMonthlyServiceCharges = 0; 
    } 

這裏是我的子類的構造函數:

public SavingsAccount(final String theNameOfOwner, final double theInterestRate) 
    { 
     BankAccount(theNameOfOwner, theInterestRate); 
     myStatusIsActive = false; 
     myWithdrawalCounter = 0; 
    } 

我收到以下錯誤:

SavingsAccount.java:7: error: constructor BankAccount in class BankAccount cannot be applied to given types; 
    { 
^
    required: String,double 
    found: no arguments 
    reason: actual and formal argument lists differ in length 

錯誤說我需要String,在我的子構造函數的BankAccount調用中的雙參數,如果我正確理解這一點。唯一的問題是它看起來像我有這些參數是正確的。任何幫助/輸入將不勝感激,因爲我剛開始編程Java!謝謝!

+0

嘗試的超代替父類的名稱 – Renjith

+0

https://開頭docs.oracle.com/javase/tutorial/java/IandI/super.html –

回答

3

這不是調用超類構造函數的方法。編譯器認爲你正試圖調用一個不存在的名爲BankAccount的方法。由於沒有對超類構造函數的顯式調用,因此它會嘗試將隱式調用插入到默認的超類構造函數中,並且該函數也不存在,從而導致出現編譯器錯誤。

使用super關鍵字來調用超類的構造函數。更改

BankAccount(theNameOfOwner, theInterestRate); 

super(theNameOfOwner, theInterestRate); 
+0

我明白了!我從來不知道這一點。我在課堂上一直沒有引起足夠的重視。非常感謝您的先生/女士。 – Trafton

1

我認爲你需要對導致錯誤的線是什麼,而不是如下:

super(theNameOfOwner, theInterestRate);