previous | start | next

Compatibility of Types

A SavingsAccount is a kind of BankAccount. It has a balance,
etc.
public class BankApp2
{
  
  public static void printAccounts(BankAccount[] acct)
  {
    for(int i = 0; i < acct.length; i++) {
      System.out.println(acct[i]);
    }
  }

  public static void main(String[] args)
  {
    BankAccount[] b = new BankAccount[3];
    BankAccount b1 = new BankAccount(1000);
    BankAccount b2 = new BankAccount(20000);
    SavingsAccount s1 = new SavingsAccount(500, 2.5);

    b[0] = b1;
    b[1] = b2;
    b[2] = s1;

    System.out.println("Original Balances:");
    printAccounts(b);

    // Make deposits:
    for(int i = 0; i < b.length; i++) {
      b[i].deposit(100);
    }

    System.out.println("\nNew Balances:");
    printAccounts(b);

  }

}

Sample run:
java BankApp2
Original Balances:
BankAccount(balance = 1000.00)
BankAccount(balance = 20000.00)
Savings Account(balance = 500.00, rate = 2.500)

New Balances:
BankAccount(balance = 1100.00)
BankAccount(balance = 20100.00)
Savings Account(balance = 600.00, rate = 2.500)


   


previous | start | next