Polymorphism
In Java, type of a variable doesn't completely determine type of object to which it refers
BankAccount aBankAccount = new SavingsAccount(1000);
// aBankAccount holds a reference to a SavingsAccount
Method calls are determined by type of actual object, not type of object reference
BankAccount anAccount = new CheckingAccount();
anAccount.deposit(1000); // Calls "deposit" from CheckingAccount
Compiler needs to check that only legal methods are invoked
Object anObject = new BankAccount();
anObject.deposit(1000); // Wrong!
Polymorphism: ability to refer to objects of multiple types with varying behavior
Polymorphism at work:
public void transfer(double amount, BankAccount other)
{
withdraw(amount); // Shortcut for this.withdraw(amount)
other.deposit(amount);
}
Depending on types of amount and other, different versions of withdraw and deposit are called
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.