(Класс сберегательного счета) Создайте класс SavingsAccount. Используйте статическую переменную AnnualInterestRate для хранения годовой процентной ставки для всех владельцев счетов. Каждый объект класса содержит частную переменную экземпляра savesBalance, указывающую сумму, которую вкладчик в настоящее время имеет на депозите. Предоставьте метод calculateMonthlyInterest для расчета ежемесячных процентов путем умножения SavingBalance на AnnualInterestRate, деленного на 12, — эти проценты должны быть добавлены к SavingBalance. Предоставьте статический метод modifyInterestRate, который устанавливает для AnnualInterestRate новое значение. Напишите программу для тестирования класса SavingsAccount. Создайте экземпляры двух объектов savesAccount, saver1 и saver2, с балансами 2000,00 и 3000,00 долларов соответственно. Установите годовую процентную ставку на 4%, затем рассчитайте ежемесячные проценты за каждый из 12 месяцев и распечатайте новые балансы для обоих вкладчиков. Затем установите годовую процентную ставку на 5%, рассчитайте проценты за следующий месяц и распечатайте новые балансы для обоих вкладчиков.

Класс сберегательного счета в Java-программе

/*
 *       Filename:  SavingsAccount.java
 *
 *    Description:  Exercise 8.6 - Savings Account Class
 *
*  @Author:  Bilal Tahir Khan Meo
 *  Website: https://codeblah.com
 *
 * =====================================================================================
 */
public class SavingsAccount{
    private static double annualInterestRate = 0.0f;
    private double savingsBalance = 0.0f;

    // constructor
    public SavingsAccount(double savingsBalance){
        setSavingsBalance(savingsBalance);
    }
    // SETTERS
    public void setSavingsBalance(double savingsBalance){
        this.savingsBalance = savingsBalance;
    }
    // update the interest rate
    public static void modifyInterestRate(double newInterestRate){
        // check for negative interest rates
        if(newInterestRate >= 0.0f)
            annualInterestRate = newInterestRate;
        else
            throw new IllegalArgumentException("interest rate must be >= 0.0f");
    }
    // GETTERS
    public double getSavingsBalance(){
        return this.savingsBalance;
    }
    public static double getAnnualInterestRate(){
        return annualInterestRate;
    }
    // calculates the monthly interest and update the savings balance
    public void calculateMonthlyInterest(){
        savingsBalance += (savingsBalance * annualInterestRate) / 12;
    }
    // return savingsBalance as string
    public String toString(){
        return String.format("%.2f", getSavingsBalance());
    }
}

Метод 2: Класс сберегательного счета в Java-программе

package savingsaccount;

public class SavingsAccount {

   //variable to store annual interest rate
        static private double annualInterestRate;
        private double savingBalance;

        //constructor method
        public SavingsAccount()
        {

        }

        //Constructor method
        public SavingsAccount(double savingBalance)
        {
                this.savingBalance=savingBalance;
        }

        //Get saving balance
        public double getSavingBalance()
        {
                return this.savingBalance;
        }
        
         // Modify interest rate by setting annual interest rate to a new value
        public static void modifyInterestRate(double newInterestRate)
        {
                annualInterestRate=newInterestRate;
        }

        //Method to calculate monthly interest 
        public void calculateMonthlyInterest()
        {
                double monthlyI; 
                monthlyI= (double)(this.savingBalance*annualInterestRate/12);
                this.savingBalance+=monthlyI;
        }


    public static void main(String[] args) {
    
                        // To test the class designed above
                //Instantiate 2 saving account objects saver1 and saver2
                SavingsAccount saver1, saver2;
                saver1 = new SavingsAccount (2000.0);
                saver2= new SavingsAccount (3000.0);
                
                int total = 0;

                //Set the annual interest rate to 4%=0.04
                SavingsAccount.modifyInterestRate (0.04);

                //Calculate monthly interest 
                saver1.calculateMonthlyInterest();
                saver2.calculateMonthlyInterest();

                //Print out the new balances for both savers
                System.out.println("This month:\nSaver 1 balance= "+ saver1.getSavingBalance());
                System.out.println("Saver 2 balance= "+ saver2.getSavingBalance());


                //Change annual interest rate to 5%=0.05
                SavingsAccount.modifyInterestRate(0.05);

                //Calculate the next month interest rate and print out balances
                saver1.calculateMonthlyInterest();
                saver2.calculateMonthlyInterest();
                System.out.println("Next month:\nSaver 1 balance= "+ saver1.getSavingBalance());
                System.out.println("Saver 2 balance= "+ saver2.getSavingBalance());

    }

Метод 3: Класс сберегательного счета в Java-программе

public class SavingsAccount
{
    private static double annualInterestRate;
    private double savingsBalance;

    protected SavingsAccount()
    {
        savingsBalance = 0;
        annualInterestRate = 0;
    }

    protected SavingsAccount(double balance)
    {
        savingsBalance = balance;
        annualInterestRate = 0;
    }

    protected void calculateMonthlyInterest()
    {
        System.out.println("Current savings balance: " + savingsBalance);
        double monthlyInterest;
        monthlyInterest = (savingsBalance * annualInterestRate)/12;
        savingsBalance += monthlyInterest;
        System.out.println("New savings balance: " + savingsBalance);
    }

    protected double getBalance()
    {
        return savingsBalance;
    }

    protected static void modifyInterestRate(double newInterestRate)
    {
        annualInterestRate = newInterestRate;
    }    
}

class SpecialSavings extends SavingsAccount
{
    protected static void modifyInterestRate()
    {
        if(SavingsAccount.getBalance() > 10000)
        {
            modifyInterestRate(.1);
        }
    }
}

class Driver
{
    public static void main(String[] args)
    {
        SavingsAccount saver1 = new SavingsAccount(2000);
        SavingsAccount saver2 = new SavingsAccount(3000);

        saver1.modifyInterestRate(.04);
        saver1.calculateMonthlyInterest();
        saver2.modifyInterestRate(.04);
        saver2.calculateMonthlyInterest();

        saver1.modifyInterestRate(.05);
        saver1.calculateMonthlyInterest();
        saver2.modifyInterestRate(.05);
        saver2.calculateMonthlyInterest();
    }
}

Первоначально опубликовано на сайте codeblah.com 15 февраля 2019 г.