Java Reference
In-Depth Information
9.3 Polymorphism
When multiple classes implement the same interface, each class implements the
methods of the interface in different ways. How is the correct method executed when
the interface method is invoked? We will answer that question in this section.
396
397
It is worth emphasizing once again that it is perfectly legalȌand in fact very
commonȌto have variables whose type is an interface, such as
Measurable x;
Just remember that the object to which x refers doesn't have type Measurable . In
fact, no object has type Measurable . Instead, the type of the object is some class
that implements the Measurable interface, such as BankAccount or Coin .
Note that x can refer to objects of different types during its lifetime. Here the variable
x first contains a reference to a bank account, then a reference to a coin.
x = new BankAccount(10000); // OK
x = new Coin(0.1, "dime"); // OK
What can you do with an interface variable, given that you don't know the class of the
object that it references? You can invoke the methods of the interface:
double m = x.getMeasure();
The DataSet class took advantage of this capability by computing the measure of
the added object, without worrying exactly what kind of object was added.
Now let's think through the call to the getMeasure method more carefully. Which
getMeasure method? The BankAccount and Coin classes provide two different
implementations of that method. How did the correct method get called if the caller
didn't even know the exact class to which x belongs?
The Java virtual machine makes a special effort to locate the correct method that
belongs to the class of the actual object. That is, if x refers to a BankAccount
object, then the BankAccount.getMeasure method is called. If x refers to a
Coin object, then the Coin.getMeasure method is called. This means that one
method call
Search WWH ::




Custom Search