java callbacks

Solutions on MaxInterview for java callbacks by the best coders in the world

showing results for - "java callbacks"
Samuel
26 Jan 2021
1interface CallBack {                   //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
2    void methodToCallBack();
3}
4
5class CallBackImpl implements CallBack {          //class that implements the method to callback defined in the interface
6    public void methodToCallBack() {
7        System.out.println("I've been called back");
8    }
9}
10
11class Caller {
12
13    public void register(CallBack callback) {
14        callback.methodToCallBack();
15    }
16
17    public static void main(String[] args) {
18        Caller caller = new Caller();
19        CallBack callBack = new CallBackImpl();       //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
20        caller.register(callBack);
21    }
22} 
23