In: Computer Science
(java ) Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all account holders. Each object of the class contains a private instance variable savingsBalance indicating the amount the saver currently has ondeposit. Provide method calculateMonthlyInterest to calculate the monthly www.oumstudents.tk interest by multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be added to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new value. Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then calculate the monthly interest and print the new balances for both savers. Then set the annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both savers.
PROGRAM :
Note : Two files are written: SavingsAccount.java containing the SavingsAccount class and TestSavings.java
/ SavingsAccount.java /
public class SavingsAccount
{
private static double annualInterestRate;
private double savingsBalance;
public void calculateMonthlyInterest()
{
savingsBalance += (savingsBalance * annualInterestRate /
12.0);
}
public static void setInterestRate(double rate)
{
annualInterestRate = rate;
}
public void setSavingsBalance(double balance)
{
savingsBalance = balance;
}
public SavingsAccount(double balance)
{
setSavingsBalance(balance);
}
public double getSavingsBalance()
{
return savingsBalance;
}
}
/ TestSavings.java /
public class TestSavings
{
public static void main(String [] arg)
{
SavingsAccount saver1 = new SavingsAccount(2000.0);
SavingsAccount saver2 = new SavingsAccount(3000.0);
SavingsAccount.setInterestRate(0.04); // set to 4%
int i;
System.out.println("Savings Account Balances");
System.out.format("%-8s %9s %9s\n", "Month", "Saver1", "Saver2");
for(i = 0; i < 13; i ++)
{
saver1.calculateMonthlyInterest();
saver2.calculateMonthlyInterest();
System.out.format("%-8d %9.2f %9.2f\n", i + 1,
saver1.getSavingsBalance(),
saver2.getSavingsBalance() );
if(i == 11)
{ //change rate after 12th iteration
SavingsAccount.setInterestRate(0.05);
}
}
}
}
OUTPUT :.