簡體   English   中英

無法從超級類中“訪問”變量

[英]Can't “access” variable from super,super class

您好,我在覆蓋存款方法時遇到問題。 我有一個BankAccount類(主要類),InterestAccount(擴展BankAccount)和IsaAccount(擴展InterestAccount)。 我無法調用余額來添加IsaAccount類的deposit方法中提到的金額。 我嘗試了多種使用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; >
        }

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

更新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);
            }

}

問題在於您嘗試從BankAccount訪問的余額變量是私有的。 當一個類擴展另一個類時,它將接收私有方法和變量,但無法訪問它們。 您可以通過將余額更改為受保護而不是私有來解決此問題。 或者,您可以在BankAccount中設置一個公共方法來設置余額。

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM