Java Reference
In-Depth Information
if(!power) // If the power is off
return 0; // Nothing works
// Wrap channel down to MAX _ CHANNEL when Min _ CHANNEL is reached
channel = channel>MIN _ CHANNEL ? --channel : MAX _ CHANNEL;
System.out.println(make + " VCR tuned to channel: "+ channel);
return channel;
}
private String make = null;
private boolean power = false;
private int MIN _ VOLUME = 0;
private int MAX _ VOLUME = 100;
private int volume = MIN _ VOLUME;
private int MIN _ CHANNEL = 0;
private int MAX _ CHANNEL = 99;
private int channel = 0;
}
Of course, we could continue, and define classes for other kinds of devices that used the remote, but
these two will be sufficient to demonstrate the principle.
Let's see how we can use the RemoteControl interface and these two classes in a working example.
Try It Out - Polymorphism Using an Interface Type
We want to demonstrate polymorphic behavior with these classes. By introducing a bit of 'randomness'
into our example, we can avoid having any prior knowledge of the objects involved. Here's the class to
operate both TV and VCR objects via a variable of type RemoteControl :
public class TryRemoteControl {
public static void main(String args[]) {
RemoteControl remote = null;
// We will create five objects to operate using our remote
for(int i = 0 ; i<5 ; i++) {
// Now create either a TV or a VCR at random
if(Math.random()<0.5)
// Random choice of TV make and screen size
remote = new TV(Math.random()<0.5 ? "Sony" : "Hitachi",
Math.random()<0.5 ? 32 : 28);
else // Random choice of VCR
remote = new VCR(Math.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
}
}
}
Search WWH ::




Custom Search