Java Reference
In-Depth Information
Sony 40 inch TV volume level: 10
Panasonic DVD Player power on.
Panasonic DVD Player tuned to channel: 1
Panasonic DVD Player volume level: 10
How It Works
The variable remote is of type RemoteControl so you can use it to store a reference to any class object
that implements the RemoteControl interface. Within the for loop, you create either a TV or a DVDPlay-
er object at random. The TV or DVDPlayer object is of a randomly chosen make, and any TV object
is either 46 inches or 40 inches — again chosen at random. The object that is created is then operated
through remote by calling its powerOnOff() , channelUp() , and volumeUp() methods. Because the type
of the object is determined at run time, and at random, the output demonstrates you are clearly seeing
polymorphism in action here through a variable of an interface type.
Using Multiple Interfaces
Of course, a RemoteControl object in the previous example can be used to call only the methods that are
declared in the interface. If a class implements some other interface besides RemoteControl , then to call the
methods declared in the second interface you need either to use a variable of that interface type to store the
object reference or to cast the object reference to its actual class type. Suppose you have a class defined as
the following:
public MyClass implements RemoteControl, AbsoluteControl {
// Class definition including methods from both interfaces...
}
Because this class implements RemoteControl and AbsoluteControl , you can store an object of type
MyClass in a variable of either interface type. For example:
AbsoluteControl ac = new MyClass();
Now you can use the variable ac to call methods declared in the AbsoluteControl interface. However,
you cannot call the methods declared in the RemoteControl interface using ac , even though the object ref-
erence that it holds has these methods. One possibility is to cast the reference to the original class type, like
this:
((MyClass)ac).powerOnOff();
Because you cast the reference to type MyClass , you can call any of the methods defined in that class.
You can't get polymorphic behavior like this though. The compiler determines the method that is called
when the code is compiled. To call the methods in the RemoteControl interface polymorphically, you have
to have the reference stored as that type. Provided you know that the object is of a class type that implements
the RemoteControl interface, you can get a reference of type RemoteControl from the reference stored in
the variable ac . Like this, for example:
Search WWH ::




Custom Search