Java Reference
In-Depth Information
object of a class that implements the
Measurable
interface, perhaps a
Coin
object
or an object of an entirely different class.
What happens when you invoke a method? For example,
BankAccount anAccount = new CheckingAccount();
anAccount.deposit(1000);
Which deposit method is called? The
anAccount
parameter has type
BankAccount
, so it would appear as if
BankAccount.deposit
is called. On
the other hand, the
CheckingAccount
class provides its own
deposit
method
that updates the transaction count. The
anAccount
field actually refers to an object
of the subclass
CheckingAccount
, so it would be appropriate if the
CheckingAccount.deposit
method were called instead.
In Java, method calls are always determined by the type of the actual object, not the
type of the object reference. That is, if the actual object has the type
CheckingAccount
, then the
CheckingAccount.deposit
method is called.
It does not matter that the object reference is stored in a field of type
BankAccount
.
As we discussed in
Chapter 9
, the ability to refer to objects of multiple types with
varying behavior is called polymorphism.
If polymorphism is so powerful, why not store all account references in variables of
type
Object
? This does not work because the compiler needs to check that only
legal methods are invoked. The
Object
type does not define a
deposit
methodȌ
the
BankAccount
type (at least) is required to make a call to the
deposit
method.
Have another look at the
transfer
method to see polymorphism at work. Here is
the implementation of the method:
public void transfer(double amount, BankAccount
other)
{
withdraw(amount);
other.deposit(amount);
}
Suppose you call
anAccount.transfer(1000, anotherAccount);
Two method calls are the result: