Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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!");
            }
        });
    }
}
share|improve this question
2  
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. –  Simon Forsberg Sep 6 '14 at 12:19

1 Answer 1

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.

share|improve this answer
    
Ok. I see. Thanks. By the way I updated my question. I think now it's much more significant. –  Alex Sep 6 '14 at 12:09
    
We need callbacks mostly for handling stuff, right? –  Alex Sep 6 '14 at 12:10

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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