Java Reference
In-Depth Information
Speaker guest;
guest = new Philosopher();
guest.speak();
guest = new Dog();
guest.speak();
In this code, the first time the speak method is called, it invokes the speak
method defined in the Philosopher class. The second time it is called, it invokes
the speak method of the Dog class. As with polymorphic references via inheri-
tance, it is not the type of the reference that determines which method gets
invoked; it is based on the type of the object that the reference points to at the
moment of invocation.
Note that when we are using an interface reference variable, we can invoke
only the methods defined in the interface, even if the object it refers to has other
methods to which it can respond. For example, suppose the Philosopher class
also defined a public method called pontificate . The second line of the following
code would generate a compiler error, even though the object can in fact respond
to the pontificate method:
Speaker special = new Philosopher();
special.pontificate(); // generates a compiler error
The problem is that the compiler can determine only that the object is a
Speaker , and therefore can guarantee only that the object can respond to the
speak and announce methods. Because the reference variable special could
refer to a Dog object (which cannot pontificate), it does not allow the invoca-
tion. If we know in a particular situation that such an invocation is valid, we
can cast the object into the appropriate reference so that the compiler will
accept it, as follows:
((Philosopher)special).pontificate();
As we can with polymorphic references based in inheritance,
an interface name can be used as the type of a method parameter.
In such situations, any object of any class that implements the
interface can be passed into the method. For example, the fol-
lowing method takes a Speaker object as a parameter. Therefore
both a Dog object and a Philosopher object can be passed into it
in separate invocations:
KEY CONCEPT
A parameter to a method can be
polymorphic, giving the method
flexible control of its arguments.
public void sayIt (Speaker current)
{
current.speak();
}
Search WWH ::




Custom Search