Before Java supports method pointers, the Java interface does not provide a good way to implement callbacks. If you are accustomed to passing function pointers that are called in the event-driven programming model, you will like this technique.
Developers familiar with the ms-windows and X Window System event-driven programming models are accustomed to passing function pointers that are invoked (that is, "callback") when an event occurs. The Java object-oriented model does not currently support method pointers, so it seems impossible to use this very good mechanism. But we don't have any idea!
Java interface Support provides a mechanism for obtaining the equivalent functionality of callbacks. The trick is to define a simple interface and declare the method that we want to invoke in that interface.
For example, suppose we want to be notified when an event occurs. We can define an interface:
public interface interestingevent{
//This is only a conventional method. So if needed,
//It can have a return value, or it can receive parameters. Public
void Interestingevent ();
}
This allows us to control any object of the class that implements the interface. Therefore, we do not have to care about any external type information. This approach is much better than the uncontrollable C function that uses the widget's data field to hold the object pointer when using C + + code for MOTIF.
The class that emits the event signal must wait for the object that implements the Interestingevent interface and call the Interestingevent () method at the appropriate time.
public class eventnotifier{
private interestingevent ie;
Private Boolean somethinghappened;
Public Eventnotifier (Interestingevent event) {
//Save Events object for later use.
ie = event;
There are no events to report.
somethinghappened = false;
}
//...
The public void DoWork () {
//checks the predicate set elsewhere.
if (somethinghappened) {
///The event signal is emitted by invoking this method of the interface.
ie.interestingevent ();
}
//...
}
// ...
}
In the example above, I use the somethinghappened predicate to track whether an event should be triggered. In many cases, calling this method is sufficient to ensure that a signal is sent to the Interestingevent ().
The code that you want to receive event notifications must implement the Interestingevent interface and pass its own reference to the event notification program.
public class CallMe implements interestingevent{
private eventnotifier en;
Public CallMe () {
//creates an event notification program and passes its own reference to it.
en = new eventnotifier (this);
}
Define the actual handler for the event. Public
void Interestingevent () {
//Oh! There must have been an event of interest!
//Perform certain actions ...
}
//...
}