Interface types, in general. You can use Runnable
(which is an interface
) as Rob suggested if your handler has no parameters and a void
return type. But it's simple enough to define your own:
interface CompletionHandler {
public void handle(String reason);
}
and then to pass it to your own class:
something.setCompletionHandler(new CompletionHandler() {
@Override
public void handle(String reason) {
...
}
});
In the other class:
void setCompletionHandler(CompletionHandler h) {
savedHandler = h;
}
and then call it just by calling the method:
savedHandler.handle("Some mysterious reason");
This sort of thing is done for "listeners" in Java Swing and Android libraries all over the place; see View.OnClickListener
, for example.
(P.S. I believe that Java 8 lambdas will be usable with all of these interface examples.)
CompletionHandler
interface just once and then overload thehandle
method when I override it? – Toombs