I have been provided with a Superclass called Account with constructor to initialize the balance, and methods to deposit, and withdraw balance, with the balance being declared private. (I cannot add or change any methods or variables in this class at all)
Then, I created a subclass called SavingsAccount with a constructor that accepts a initial balance. If the initial balance is negative, then the account should be initialized with a balance of 0. Also, it contains two over-ridden methods, deposit and withdraw, which checks the amount being deposited and withdrawn to see if it is possible or not. Here's the code that I've been provided (Account) and that I've written (SavingsAccount).
I tried calling the super() inside a if-else conditional, but Java gives an error that super()call has to be the first line of the constructor. So, how do I get around this? Also, since I don't have a setBalance() method in the provided Account class, how can I set the balance from my deposit and withdraw methods in my SavingsAccount class?
Account.Java (Provided for testing, and cannot modify)
public class Account
{
private double balance;
// Constructor to initialise balance
public Account( double amount )
{
balance = amount;
}
// Overloaded constructor for empty balance
public Account()
{
this(0.0);
}
public void deposit( double amount )
{
balance += amount;
}
public void withdraw( double amount )
{
balance -= amount;
}
public double getBalance()
{
return balance;
}
}
SavingsAccount.java (Written by me)
public class SavingsAccount extends Account
{
private int overDraftCount = 0;
public SafeAccount(double initial_balance)
{
if(initial_balance <0)
{
super(0.00);
}
else
{
super(initial_balance);
}
}
@Override
public void deposit(double amount)
{
if(amount < 0)
{
??? = getBalance();
}
else
{
??? = getBalance()+ amount;
}
}
@Override
public void withdraw(double amount)
{
if(amount < getBalance())
{
overDraftCount++;
??? = getBalance();
}
else
{
??? = getBalance() - amount;
}
}
public int overdraftAttempts()
{
return overDraftCount;
}
}
Account
? – Elliott Frisch