Ibrahim :
I wrote a java program in which the subclass is BankAccount
and SavingsAccount
is the subclass of it, and I am doing some transactions with it but the balance is not getting updated and only shows 0.00 as the output.
Here is my code:
public class BankAccountTest {
public static void main(String[] args) {
SavingsAccount savingsAccount = new SavingsAccount(879101,0,0.04);
savingsAccount.deposit(500);
savingsAccount.withdraw(500);
savingsAccount.deposit(1500);
savingsAccount.deposit(500);
savingsAccount.withdraw(500);
savingsAccount.deposit(5000);
savingsAccount.deposit(500);
savingsAccount.annualCredit();
System.out.println(savingsAccount);
}
}
class BankAccount {
private int accountNumber;
protected double balance;
public BankAccount( int accountNumber, double balance)
{
this.accountNumber = accountNumber;
this.balance = balance;
}
public int getAccountNumber () {
return accountNumber;
}
public double getBalance () {
return balance;
}
public void setAccountNumber ( int accountNumber){
this.accountNumber = accountNumber;
}
public void setBalance ( double balance){
this.balance = balance;
}
public void deposit ( double amount){
balance = balance + amount;
}
public void withdraw ( double amount){
if (amount <= balance)
balance = balance - amount;
}
public String toString () {
return String.format("Account Number=%d%nBalance=%.2f%n", accountNumber, balance);
}
}
class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
}
public void deposit(double amount){
balance = balance+(interestRate*amount);
}
public void withdraw(double amount) {
super.withdraw(amount);
}
public void annualCredit(){
if (balance<=1000){
balance=interestRate*balance;
}
else if(balance<=5000){
balance=2*interestRate*balance;
}
else if(balance>5000){
balance=3*interestRate*balance;
}
}
public double getInterestRate(){
return interestRate;
}
public String toString(){
System.out.println("Account= "+getAccountNumber()+"\nBalance= "+balance+"\nInterestRate= "+interestRate);
return null;
}
}
And the output:
Account= 879101
Balance= 0.0
InterestRate= 0.0
null
Elliott Frisch :
You never set interestRate
in your SavingsAccount
constructor. Since deposits are multiplied by that (and it's zero) it never updates.
public SavingsAccount(int accountNumber, double balance, double interestRate) {
super(accountNumber, balance);
this.interestRate = interestRate;
}
Also, interest should probably not be paid on deposit.
public void deposit(double amount) {
balance += amount;
}