Java Reference
In-Depth Information
Forexample, a plotting function could receive a pointer to a function that takes
an x axis value as an argument and returns a value for the y axis ( sin(x), cos(x) , for
example). The plotting function could then plot any such function whose pointer
is passed to it without knowing explicitly the name of the function.
Java, however, does not provide pointers (actual memory addresses), only
object references. A reference cannot refer to a method. Instead, Java provides
interfaces for callbacks. In this case, a library method holds a reference to an inter-
face in its parameter list and then invokes a method declared in that interface. The
programmer provides a class that implements the required interface and provides
an object reference to the library method. When the library method invokes the
required interface method, the concrete implementation in the provided object is
invoked.
In the following code we see that the aFunc(Switchable sw) method
invokes the getState() method of the Switchable interface. An instance
of any class that implements the Switchable interface can thus be passed to
aFunc() . This technique provides the same generality as pointer callbacks in
C. The only drawback is that a class must implement the interface.
public class TestCallBack {
public static void main(String [] args) {
Switchable[] switches = new Switchable[3];
switches[0] = new Relay();
switches[1] = new Relay();
switches[2] = new Valve();
// Pass Switchable objects to aFunc ()
for (int i = 0; i < 3; i++) {
aFunc (switches[i]);
}
}
// Receive Switchable objects and call their getState ()
void aFunc (Switchable sw) {
if (sw.getState ()) doSomething ();
}
}
... See previous example for Relay and Valve definitions .
4.5.3 More about interfaces
Interfaces can extend other interfaces, much like class inheritance. All the meth-
ods declared in the super-interface are effectively present in the sub-interface.
Unlike classes, however, interfaces can participate in multiple inheritance. The
 
Search WWH ::




Custom Search