Is this a proper callback implementation in Java? 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!");
            }
        });
    }
}
Yes, that is an implementation of a callback. There are some things to note though:


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
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).
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(() -&gt; System.out.println("Printed!"));
}


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