2015-05-07 128 views
1

你好我有一個覆蓋存款方法的問題。我有一個BankAccount類(主要的),InterestAccount(擴展了BankAccount)和IsaAccount(擴展了InterestAccount)。我無法撥打餘額以添加IsaAccount類的存款方式中提到的金額。我已經嘗試了很多使用getBalance,super(balance),super.getBalance等的方法。這耗盡了我很多......我瀏覽了許多類似的話題,但找不到解決這個特定問題的辦法。我必須做一個存款方法,這樣我才能把錢存入IsaAccount對象。不能從超級,超級類別「訪問」變量

public class BankAccount { 

    private int balance; 

    public BankAccount() { 
      balance = 0; 
     } 

    ...................... 


    public class InterestAccount extends BankAccount { 

     private int interestRate; 
     private int minimumBalance; 


     public InterestAccount() { 
      super();  
      interestRate = 0; 
      minimumBalance = 100; 
     } 

    ...................... 

    public class IsaAccount extends InterestAccount { 

     private int depositRemaining; 

     public IsaAccount() { 
      super(); 
      depositRemaining = 0; 
     } 

     public IsaAccount(int balance, int interestRate, int minimumBalance, int depositRemaining) { 
      super(balance, interestRate, minimumBalance); 
      this.depositRemaining = depositRemaining; 

     } 

     @Override 
      public void deposit(int amount) { 
      if (amount <= depositRemaining) 
       <HERE I NEED TO CALL BALANCE(not sure whether I have to use get 
       methods or what) e.g balance = balance + amount; > 
     } 

    ...................... 
+0

看來你嘗試*控*有沒有一種方法已在父母中定義。你也調用不存在的父構造函數。 –

+0

你應該包括完整的BankAccount類定義 – Typo

+0

流行測驗:「私人」是什麼意思/做什麼? – immibis

回答

2

更新的BankAccount已經設置和獲取類似

class BankAccount { 

    private int balance; 

    public BankAccount() { 
     balance = 0; 
    } 

    public int getBalance() { 
     return this.balance; 
    } 

    public void setBalance(int balance) { 
     this.balance = balance; 
    } 
} 

然後用這個方法(當然,因爲你必須使用@Override我假設它在父類中確實存在過,如果沒有,那麼刪除@Override

 @Override 
    public void deposit(int amount) { 
     if (amount <= depositRemaining){ 
      setBalance(getBalance() + amount); 
      } 

} 
+0

謝謝,先生。它工作得很好,是的,我在主類中有一個存款方法。再次感謝! – Lazio

+1

當然,做:) – Lazio

0

問題是你試圖從BankAccount訪問的平衡變量是私有的,當一個類擴展另一個類時,它收到es私有方法和變量,但它不能訪問它們。您可以通過將平衡更改爲受保護而非私人來解決此問題。或者您可以在BankAccount中設置一個公開方法來設置餘額。

  1. protected int balance;而不是private int balance;

  • public void setBalance(int balance){ this.balance = balance; } public int getBalance(){ return balance; }
  • +0

    2號不足,因爲目標是更新'balance'的值。還需要一個(受保護的)setter。 –

    +0

    不是很完美,因爲兩者都是必需的:setter和getter,因爲我們想調用'setBalance(getBalance()+ amount)' –

    +0

    是的,我匆忙地這麼做。 – ejmejm