How does the @Override
method work in Java?
I'm trying to learn the @Override
method and how inheriting works in Java. I believe I've gathered how child and parent classes work.
Below I have one driver class, one parent class and then two child classes.
What I'm trying to do is have the toString
method in the SimpleBankAccount
class called. However, the toString methods in the child classes are getting called.
public class AccountsDriver{
final public static double INTEREST_RATE = 0.01; // 1%
public static void main( String[] args ){
CheckingAccount checking = new CheckingAccount( 100.0 );
SavingAccount savings = new SavingAccount( 1000.0, INTEREST_RATE );
double monthlyExpenses = 756.34;
int electricBillCheckNum = 2123;
double electricBill = 60.34;
int registationCheckNum = 2124;
double registration = 50.00;
double dinnerMoney = 55.32;
double futureCar = 200.0;
double textbook = 90.0;
checking.deposit( monthlyExpenses );
checking.processCheck( electricBillCheckNum, electricBill );
checking.withdraw( dinnerMoney );
checking.processCheck( registationCheckNum, registration );
System.out.print( checking.toString() );
savings.deposit( futureCar );
savings.applyInterest( );
savings.withdraw( textbook );
System.out.print( savings.toString() );
}
}
public class SimpleBankAccount
{
protected double balance;
public boolean withdraw(double amount){
if (balance - amount >= 0){
balance -= amount;
return true;
}else{
return false;
}
}
public String toString(){
//display balance as currency
String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
return "Balance: " +balanceStr+ "\n";
}
}
public class CheckingAccount extends SimpleBankAccount
{
int lastCheck;
public CheckingAccount(double amount){
balance = amount;
}
public boolean processCheck(int checkNum, double amount){
if (lastCheck == checkNum){
return false;
}else{
balance -= amount;
lastCheck = checkNum;
return true;
}
}
public String toString(){
//display the balance as currency
String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
return "Checking Account: \n Balance: " +balanceStr+ "\n Last processed check: " +lastCheck;
}
}
public class SavingAccount extends SimpleBankAccount
{
double interestRate;
public SavingAccount(double amount, double interestRate){
balance = amount;
this.interestRate = interestRate;
}
public void applyInterest(){
balance = (balance*interestRate)+balance;
}
public String toString(){
//display balance as currency
String balanceStr = NumberFormat.getCurrencyInstance().format(balance);
return "Saving Account: \n Balance: " +balanceStr+ "\n APR: " +interestRate;
}
}
Can someone point out what I'm doing wrong?