您好,我在覆盖存款方法时遇到问题。我有一个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);
}
}
关于java - 无法从 super 类中“访问”变量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30090438/