您好我在覆盖存款方法时遇到问题。我有一个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 :(得分:2)
更新BankAccount以设置并获得
echo "$A"\_new
然后使用此方法(当然,因为您使用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
答案 1 :(得分:0)
问题是您尝试从BankAccount访问的余额变量是私有的。当一个类扩展另一个类时,它会接收私有方法和变量,但它无法访问它们。您可以通过将余额更改为受保护而非私有来解决此问题。或者你可以在BankAccount中设置一个公共方法来设置余额。
@Override
public void deposit(int amount) {
if (amount <= depositRemaining){
setBalance(getBalance() + amount);
}
}
而不是protected int balance;
或
private int balance;