I am trying to understand callbacks in Java, but it's confusing me a lot. I know callbacks are passed as an object by implementing interface. But I'm not able to understand how the functions of those passed objects in arguments are invoked. I took this example
interface ClickEventHandler {
public void handleClick();
}
//Step 2: Create a callback handler
//implementing the above interface
class ClickHandler implements ClickEventHandler {
public void handleClick() {
System.out.println("Clicked");
}
}
//Step 3: Create event generator class
class Button {
public void onClick(ClickEventHandler clickHandler) {
clickHandler.handleClick();
}
}
public class Tester {
public static void main(String[] args) {
Button button = new Button();
ClickHandler clickHandler = new ClickHandler();
//pass the clickHandler to do the default operation
button.onClick(clickHandler);
Button button1 = new Button();
//pass the interface to implement own operation
button1.onClick(new ClickEventHandler() {
@Override
public void handleClick() {
System.out.println("Button Clicked");
}
});
}
}
Output is
```none
Clicked Button
Clicked.
I mean to invoke the function of passed objects we need to register it and call the functions. How does it work in case of listeners? It would be helpful if someone guide me in understanding this.
interface
. This describes the expected functionality which might be executed by the object been observed. So, passing an instance of an object which implementsClickEventHandler
means that object can call thehandleClick
, because it guarantees the implementation (hay polymorphism!)