Java Reference
In-Depth Information
10.3 Polymorphism via Interfaces
Now let's examine how we can create polymorphic references using
interfaces. As we've seen many times, a class name can be used to
declare the type of an object reference variable. Similarly, an inter-
face name can be used as the type of a reference variable as well. An
interface reference variable can be used to refer to any object of any
class that implements that interface.
Suppose we declare an interface called Speaker as follows:
KEY CONCEPT
An interface name can be used to
declare an object reference variable.
public interface Speaker
{
public void speak();
public void announce (String str);
}
The interface name, Speaker , can now be used to declare an object reference
variable:
Speaker current;
The reference variable current can be used to refer to any object of
any class that implements the Speaker interface. For example, if we
define a class called Philosopher such that it implements the Speaker
interface, we can then assign a Philosopher object to a Speaker refer-
ence as follows:
KEY CONCEPT
An interface reference can refer to
any object of any class that imple-
ments that interface.
current = new Philosopher();
This assignment is valid, because a Philosopher is a Speaker . In this sense
the relationship between a class and its interface is the same as the relationship
between a child class and its parent. It is an is-a relationship. And that relationship
forms the basis of the polymorphism.
The flexibility of an interface reference allows us to create polymorphic refer-
ences. As we saw earlier in this chapter, using inheritance, we can create a poly-
morphic reference that can refer to any one of a set of objects as long as they are
related by inheritance. Using interfaces, we can create similar polymorphic refer-
ences among objects that implement the same interface.
For example, if we create a class called Dog that also implements the Speaker
interface, it can be assigned to a Speaker reference variable as well. The same
reference variable, in fact, can at one point refer to a Philosopher object and then
later refer to a Dog object. The following lines of code illustrate this:
 
Search WWH ::




Custom Search