Example of Inheritance

  1. Recall a BankAccount class:

        public class BankAccount
        {
          private double balance;
    
          public void deposit(double amount)
          {
             balance = balance + amount;
          }
    
          public void withdraw(double amount)
          {
             if ( amount <= balance )
                balance = balance - amount;
             else
                System.out.println("Insufficient funds");
          }
    
          public double getBalance()
          {
             return(balance);
          }
       }
    

  2. We want to define a SavingsAccount class that has the following functionalities:

    Conclusion: we need

  3. NOTE:

    SavingsAccount class definition:
       public class SavingsAccount extends BankAccount
       {
          private double interestRate;
    
          public SavingsAccount(double rate)
          {
             interestRate = rate;
          }
    
          public void addInterest()
          {
             double interest;
    
             interest = getBalance() * interestRate/100;     
             deposit(interest);
          }
       }
    
    

    Result:

    A bit of advise:

  4. DEMO programs:

  5. NOTE: