Java Reference
In-Depth Information
TRY IT OUT: Polymorphism Using an Interface Type
You want to demonstrate polymorphic behavior with these classes. By introducing a bit of “randomness”
into the example, you can avoid having any prior knowledge of the objects involved. Here's the class to
operate both TV and DVD player objects via a variable of type RemoteControl :
import static java.lang.Math.random;
public class TryRemoteControl {
public static void main(String args[]) {
RemoteControl remote = null;
// You will create five objects to operate using our remote
for(int i = 0 ; i<5 ; ++i) {
// Now create either a TV or a DVD Player/Recorder at random
if(random()<0.5)
// Random choice of TV make and screen size
remote = new TV(random()<0.5 ? "Sony" : "Hitachi",
random()<0.5 ? 46 : 40);
else // Random choice of DVD Player/Recorder
remote = new DVDPlayer(random()<0.5 ? "Panasonic": "JVC");
// Now operate it, whatever it is
remote.powerOnOff();
// Switch it on
remote.channelUp();
// Set the next
channel up
remote.volumeUp(10);
// Turn up the sound
}
}
}
Directory "TryRemoteControl"
This should be in the same directory as the source files for the two classes and the interface defined earli-
er. When you compile and run this, you should see output recording a random selection of five TV and
DVD player objects operated by the RemoteControl variable. I got the following:
JVC DVD Player power on.
JVC DVD Player tuned to channel: 1
JVC DVD Player volume level: 10
Panasonic DVD Player power on.
Panasonic DVD Player tuned to channel: 1
Panasonic DVD Player volume level: 10
Sony 46 inch TV power on.
Sony 46 inch TV tuned to channel: 1
Sony 46 inch TV volume level: 10
Sony 40 inch TV power on.
Sony 40 inch TV tuned to channel: 1
Search WWH ::




Custom Search