簡體   English   中英

引用超類幫助中的字段的java子類方法!

[英]java subclass method referring to field in superclass help!

我有一個名為Savingsaccount的子類。 我希望Savingsaccount中的method(addInterest)引用超類中稱為balance的字段。 它說平衡可以私人訪問。 我如何解決這個問題? 我不允許將超類中的字段設置為私有以外的其他任何字段。 感謝您的幫助。 這是儲蓄帳戶中的方法。

public void addInterest()
{
    deposit(balance * interestRate / 100);
}

創建一個getter方法,如下所示:

public abstract class MySuperClass {
    private float balance;

    protected float getBalance() {
        return balance;
    }
}

public class SavingsAccount extends MySuperClass {
    public void addInterest() {
        deposit(super.getBalance() * interestRate / 100);
    }

    private void deposit(..) {
        ...
    }
}

您可以在超類中添加吸氣劑嗎? 如果它是私有的,則它是不可訪問的-句點-因此,您將不得不使其受到保護或添加get方法:

public class YourSuperClass {
    public YourType getSuperClassField() {
        return superClassField;
    }
}

(從技術上講,您可以使用反射-但這在IMO中是一個非常糟糕的主意)

protected BalanceType getBalance() { return this.balance; }

在超類中,其中BalanceTypebalance類型(您未指定)

如果每個人都有源代碼,則可以添加getter方法,否則可以使用反射來訪問私有成員進行訪問。

暫無
暫無

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

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