Java Reference
In-Depth Information
4.5.1 Interfacing classes
The term
interface
is a very suitable name for these kinds of abstract classes
because they can provide a systematic approach to adding access to a class. That
is, they can provide a common
interface
.
Forexample, say that we have classes
Relay
and
Valve
that are completely
independent, perhaps written by two different programmers. The class
Test
could communicate easily with both of these classes if they were modified to
implement the same interface. Let's define an interface called
Switchable
,
which holds a single method called
getState()
,asin
public interface Switchable
{
public boolean getState ();
}
We want both the
Relay
and
Valve
classes to implement
Switchable
and
provide a
getState()
method that returns a value
true
or
false
that indicates
whether a relay or a valve is in the on or off state.
In the code below we show the class
Test
that references instances of
Relay
and
Valve
as
Switchable
types.
Test
can then invoke their respective
getState()
methods to communicate with them.
class
Test
{
public static void main (String[] args) {
Switchable[] switches = new Switchable[2];
switches[0] = new Relay ();
switches[1] = new Valve ();
for (int i
=
0; i
<
2; i++)
{
if (switches[i].getState ()) doSomething (i);
}
}
}
class
Relay
implements Switchable
{
boolean setting = false;
// Implement the interface method getState()
boolean getState () {
return setting;
}
..
other code . .
}
class
Valve
implements Switchable {
boolean valveOpen = false;
Search WWH ::
Custom Search