Java Reference
In-Depth Information
// Implement the interface method getState()
boolean getState () {
return valveOpen;
}
.. other code . .
}
interface Switchable {
boolean getState ();
}
So we see that an interface can serve literally to interface otherwise incompatible
classes together. The modifications required for the classes Relay and Valve
involve only the implementation of the interface Switchable . Class Test
illustrates how we can treat instances of Relay and Valve both as the type
Switchable and invoke getState() to find the desired information for the
particular class. If additional classes that represent other components with on/off
states are created for our system simulation, we can ask that they also implement
Switchable .
Note that if we don't have the source code for Valve and Relay ,wecould still
create subclasses of them and have those subclasses implement Switchable .
Forexample,
class SwitchableValve extends Valve implements Switchable {
boolean getState () {
...
}
}
4.5.2 Interfaces for callbacks
With the C language, programmers often use pointers to functions for tasks
such as passing a pointer in an argument list. The receiving function can use the
pointer to invoke the passed function. This technique is referred to as a “callback”
and is very useful in situations where you want to invoke different functions
without needing to know which particular one is being invoked or when library
code needs to invoke a function that is supplied by a programmer using the
library.
Search WWH ::




Custom Search