Java Reference
In-Depth Information
This should be in the same directory as the other two class, and the interface. When you compile and
run this, you should see output recording a random selection of five TV and VCR objects operated by
our RemoteControl variable. I got:
Sony 28 inch TV power on.
Sony 28 inch TV tuned to channel: 1
Sony 28 inch TV volume level: 10
Panasonic VCR power on.
Panasonic VCR tuned to channel: 1
Panasonic VCR volume level: 10
Sony 32 inch TV power on.
Sony 32 inch TV tuned to channel: 1
Sony 32 inch TV volume level: 10
JVC VCR power on.
JVC VCR tuned to channel: 1
JVC VCR volume level: 10
Sony 28 inch TV power on.
Sony 28 inch TV tuned to channel: 1
Sony 28 inch TV volume level: 10
How It Works
The variable remote is of type RemoteControl so we can use it to store a reference to any class
object that implements the RemoteControl interface. Within the for loop, we create either a TV or a
VCR object at random. The TV or VCR object will be of a randomly chosen make, and any TV object will
be either 28" or 32" - again chosen at random. The object that is created is then operated through
remote by calling its powerOnOff() , channelUp() , and volumeUp() methods. Since the type of
the object is determined at runtime, and at random, the output demonstrates we 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 only be used to call 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 would either need 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 we have a class defined as:
public MyClass implements RemoteControl, AbsoluteControl {
// Class definition including methods from both interfaces...
}
Since this class implements RemoteControl and AbsoluteControl , we can store an object of type
MyClass in a variable of either interface type. For example:
AbsoluteControl ac = new MyClass();
Now we can use the variable ac to call methods declared in the AbsoluteControl interface.
However, we cannot call the methods declared in the RemoteControl interface using ac , even though
the object reference that it holds has these methods. One possibility is to cast the reference to the
original class type, like this:
Search WWH ::




Custom Search