1
\$\begingroup\$

I have a code which I believe is callback implementation. Can you please provide your more experienced opinions on whether this is a good way to callback?

public interface Callback {
    void run();
}

Test of callback with anonymous function

public class Test {
    static void method (Callback callback){
        callback.run();
    }

    public static void main(String[] args) {
        method(new Callback() {
            @Override
            public void run() {
                System.out.println("Printed!");
            }
        });
    }
}
\$\endgroup\$
1
  • 2
    \$\begingroup\$ Welcome to Code Review! After having received answers, please do not add revised versions of your code to your question or modify your previous code in such a way that it invalidates answers. See our meta question Can I edit my own question to include revised code? for what you can do after having received answers to your question. \$\endgroup\$ Commented Sep 6, 2014 at 12:19

1 Answer 1

3
\$\begingroup\$

Yes, that is an implementation of a callback. There are some things to note though:

  1. Callbacks in Java are seldom called Callbacks, but rather 'events' or 'listeners' (which is why you probably found it hard to search for the concepts in Java). The most common Listeners are likely in the AWT/Swing library, like ActionListener

  2. having a run() method on the callback is a poor choice of name, because it confuses it with the Runnable interface (which, in a sense, is a callback of sorts too).

  3. Java8 introduces functional interfaces which allows you to extend your callback in more concise ways. You should consider it.

Using a functional interface:

If you were to use your interface, but declare it as a functional interface to make it obvious (it is not required to declare it as functional, the compiler can automatically detect it...):

@FunctionalInterface
public interface Callback {
    void run();
}

Then, in your code, you can have:

static void method (Callback callback){
    callback.run();
}

public static void main(String[] args) {
    method(() -> System.out.println("Printed!"));
}

(you can also use the anonymous class, but the functional-interface implementation is.... neater.

\$\endgroup\$
2
  • \$\begingroup\$ Ok. I see. Thanks. By the way I updated my question. I think now it's much more significant. \$\endgroup\$
    – Alex
    Commented Sep 6, 2014 at 12:09
  • \$\begingroup\$ We need callbacks mostly for handling stuff, right? \$\endgroup\$
    – Alex
    Commented Sep 6, 2014 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.