Reputation: 105
Hello I have a problem at overriding a deposit method. I have a BankAccount class (main one), InterestAccount (that extends BankAccount) and IsaAccount (that extends InterestAccount). I can't call the balance to add the amount mentioned in the deposit method of the IsaAccount class. I have tried many ways using getBalance, super(balance), super.getBalance etc. Nothing works. This exhausts me so much... I looked through many similar topics but can't find a solution to this particular problem. I have to make a deposit method so I could deposit money to the IsaAccount object.
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; >
}
......................
Upvotes: 1
Views: 820
Reputation: 86
The problem is that the balance variable you are trying to access from BankAccount is private. When a class extends another class, it receives private methods and variables, but it cannot access them. You could either fix this by changing balance to protected, rather than private. Or you could make a public method in BankAccount that sets the balance.
protected int balance;
rather than private int balance;
or
public void setBalance(int balance){
this.balance = balance;
}
public int getBalance(){
return balance;
}
Upvotes: 0
Reputation: 4785
Update BankAccount to have set and get like
class BankAccount {
private int balance;
public BankAccount() {
balance = 0;
}
public int getBalance() {
return this.balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
}
Then use this method (Naturally since you have use @Override
I am assuming it does exist in a parent class too if not then remove @Override
@Override
public void deposit(int amount) {
if (amount <= depositRemaining){
setBalance(getBalance() + amount);
}
}
Upvotes: 2