2

I was looking at How do I perform a JAVA callback between classes?. And the first answer, answered my query.

interface CallBack {
    void methodToCallBack();
}

class CallBackImpl implements CallBack {
    public void methodToCallBack() {
        System.out.println("I've been called back");
    }
}

class Caller {

    public void register(CallBack callback) {
        callback.methodToCallBack();
    }

    public static void main(String[] args) {
        Caller caller = new Caller();
        CallBack callBack = new CallBackImpl();
        caller.register(callBack);
    }
} 

However, it challenges my concept of callback from scripting languages like JavaScript. Where implementation of callback functions are passed from the caller. for example,

function IWillCallTheCallBack(callback) {
      callback();
}

Can anyone explain the difference between callback in Java vs other programming language.

Community
  • 1
  • 1
Veer Shrivastav
  • 5,434
  • 11
  • 53
  • 83
  • 1
    Callbacks aren't really used in Java. In Java we achieve polymorphism through inheritance and interfaces instead. We can pass around instances of classes instead of functions. – byxor Jan 15 '17 at 13:23

1 Answers1

0

One possible way might be to use a lambda of a Runnable. The advantage of this is that it can be called back asynchronously, on another Thread, if you want.

public class CallbackTest {

    public static void run(Runnable callback) {
        callback.run();
    }

    public static void main(String[] args) {
        run(()-> System.out.println("I've been called"));
    }
}
Stewart
  • 17,616
  • 8
  • 52
  • 80