Polymorphism

BankAccount aBankAccount = new SavingsAccount(1000);
//  aBankAccount holds a reference to a SavingsAccount

BankAccount anAccount = new CheckingAccount();
anAccount.deposit(1000); // Calls "deposit" from CheckingAccount

Object anObject = new BankAccount();
anObject.deposit(1000); // Wrong!

public void transfer(double amount, BankAccount other)
{
   withdraw(amount); // Shortcut for this.withdraw(amount)
   other.deposit(amount);
}

Click here for Programs of Bank Account Tester

If a is a variable of type BankAccount that holds a non-null reference, what do you know about the object to which a refers?

   Answer: The object is an instance of BankAccount or one of its subclasses.


If a refers to a checking account, what is the effect of calling a.transfer(1000, a)?

   Answer: The balance of a is unchanged, and the transaction count is incremented twice.