What is a callback method in Java? (Term seems to be used loosely)

java callbacks explained
java asynchronous callback
callback methods
callback in java 8
java void method callback
callback function geeksforgeeks
java thread callback
callback handler in java

I don't understand what a callback method is and I have heard people use that term very loosely. In the Java world, what is a callback method? If someone could provide some example code of a Java callback method with an explanation, it would be a great help in my Java learning journey.

Thank you in advance.

A callback is a piece of code that you pass as an argument to some other code so that it executes it. Since Java doesn't yet support function pointers, they are implemented as Command objects. Something like

public class Test {
    public static void main(String[] args) throws  Exception {
        new Test().doWork(new Callback() { // implementing class            
            @Override
            public void call() {
                System.out.println("callback called");
            }
        });
    }

    public void doWork(Callback callback) {
        System.out.println("doing work");
        callback.call();
    }

    public interface Callback {
        void call();
    }
}

A callback will usually hold reference to some state to actually be useful.

By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback.

Callback function, is passed that refers to the location of a function. By making the callback implementation have all the dependencies to your code, you gain indirection between your code and the code that is executing the callback. In simple terms, callback mechanism refers to calling a function with another function as an argument.

A callback method in java is a method that gets called when an event (call it E) occurs. Usually you can implement that by passing an implementation of a certain interface to the system that is responsible for triggering the event E (see example 1).

Also in bigger and more complex systems you simply can annotate a method and the system will identify all annotated methods and will call them when the event occurs (see example 2). Of course the system defines what parameters the method should receive and other constraints.

Example 1:

public interface Callback {
    //parameters can be of any types, depending on the event defined
    void callbackMethod(String aParameter);
}


public class CallbackImpl implements Callback {
    void callbackMethod(String aParameter) {
     //here you do your logic with the received paratemers
     //System.out.println("Parameter received: " + aParameter);

    }
}

//.... and then somewhere you have to tell the system to add the callback method
//e.g. systemInstance.addCallback(new CallbackImpl());

Example 2:

//by annotating a method with this annotation, the system will know which method it should call. 
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CallbackAnnotation {}


public class AClass {

    @CallbackAnnotation
    void callbackMethod(String aParameter) {
     //here you do your logic with the received paratemers
     //System.out.println("Parameter received: " + aParameter);

    }
}

//.... and then somewhere you have to tell the system to add the callback class
//and the system will create an instance of the callback class
//e.g. systemInstance.addCallbackClass(AClass.class);

Callback functions in Java, to notify a piece of code i.e. a method, which piece of code to execute, i.e. another method, when it is needed. Java's object-oriented model does not currently support method pointers, and thus seems to preclude using this comfortable mechanism. But all is not lost! Java's support of interfaces provides a mechanism by which we can get the equivalent of callbacks. The trick is to define a simple interface that declares the method we wish to be invoked.

In Simple Words... In plain English, a callback function is like a Worker who "calls back" to his Manager when he has completed a Task.

How are they different from calling one function from another function taking some context from the calling function? It is true that you are calling a function from another function, but the key is that the callback is treated like an Object, so you can change which Function to call based on the state of the system (like the Strategy Design Pattern).

How can their power be explained to a novice programmer? The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server. Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze up" while downloading the new data, or you would need to refresh the entire page rather than just part of it. With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.

Some code without a callback:

     function grabAndFreeze() {
    showNowLoading(true);
    var jsondata = getData('http://yourserver.com/data/messages.json');
    /* User Interface 'freezes' while getting data */
    processData(jsondata);
    showNowLoading(false);
    do_other_stuff(); // not called until data fully downloaded
        }

      function processData(jsondata) { // do something with the data
    var count = jsondata.results ? jsondata.results.length : 0;
     $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
     $('#results_messages').html(jsondata.results || '(no new messages)');
       }

With Callback: Here is an example with a callback, using jQuery's getJSON:

    function processDataCB(jsondata) { // callback: update UI with results
   showNowLoading(false);
   var count = jsondata.results ? jsondata.results.length : 0;
   $('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
   $('#results_messages').html(jsondata.results || '(no new messages)');
          }

`   `function grabAndGo() { // and don't freeze
    showNowLoading(true);
    $('#results_messages').html(now_loading_image);
    $.getJSON("http://yourserver.com/data/messages.json", processDataCB);
    /* Call processDataCB when data is downloaded, no frozen User Interface!                              
    do_other_stuff(); // called immediately

Callback using Interfaces in Java, (Term seems to be used loosely) (5 answers) In Java, the concept of callback is implemented differently. In object-oriented programming languages without function-valued arguments, such as in Java before its 1.7 version, callbacks Callbacks are most easily described in terms of the telephone system. Is there a way to pass a call back function in a Java method? The behavior I'm trying to mimic is a .Net Delegate being passed to a function. I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

In simple terms, callback mechanism refers to calling a function with another function as an argument. In languages like C,C++ this is done by passing function pointers as arguments but java doesn't have the concept of pointers. The workaround is interfaces. We pass reference to interfaces instead of pointers. Your understanding will be crystal clear after understanding the code below. To also show the real world applications, imagine purchasing a mouse and a mouse pad. The mouse pad price is fixed but mouse price differs by brand.

interface mouse
{
    double mousePrice();
}
class BrandA implements mouse
{
    public double mousePrice()          //note that public access modifier is needed as all methods of interface are public are by default and when you override them
    //you cannot use any access modifier more restrictive
    {
        return 100;
    }

}

class BrandB implements mouse
{
    public double mousePrice()
    {
        return 200;
    }

}

class Simple
{
    static void total(mouse t)
    {
        double mousepad = 20;
        double mousep = t.mousePrice();
        System.out.println(mousepad + mousep);
    }
    public static void main(String args[])
    {
        mouse ob = new BrandA();        //upcasting. 
        total(ob);
    }
}

What are callback methods?, I don't understand what a callback method is and I have heard people use that term very loosely. In the java world what is a call back method? If someone could​  What is a callback method in java? Term seems to be used loosely before_destroy callback not stopping record from being deleted

@Sotirios Delimanolis answer is good but I wanted to give clear example which explains callbacks in a way how listeners works - following approach is greatly adopted by android library.

class RemoteClass {

    private OnChangeListener mOnChangeListener;

    void makeSomeChanges() {
        /*
        .. do something here and call callback
        */
        mOnChangeListener.onChanged(this, 1);
    }

    public void setOnChangeListener(OnChangeListener listener) {
        mOnChangeListener = listener;
    }

    public interface OnChangeListener {
        public void onChanged(RemoteClass remoteClass, int test);
    }
}

There is a class built my someone, which goes by name RemoteClass and tells your class to reference the callback by passing implementation of OnChangeListener interface to setOnChangeListener method.

class Test {

    public static void main(String[] args) {    
        RemoteClass obj = new RemoteClass();
        obj.setOnChangeListener(demoChanged);
        obj.makeSomeChanges();
    }

    private static RemoteClass.OnChangeListener demoChanged = new RemoteClass.OnChangeListener() {
        @Override
        public void onChanged(RemoteClass remoteClass, int incoming) {
            switch (incoming) {
                case 1:
                    System.out.println("I will take appropriate action!");
                    break;
                default:
                    break;
            }
        }
    };
}

Now your class has finished doing its task and RemoteClass does its work and upon calling makeSomeChanges whenever necessary results in onChanged method execution using mOnChangeListener reference.

what do you mean by callbacks?, Java interfaces provide a good way to implement callbacks until Java supports not currently support method pointers, and thus seems to preclude using this In that example, I used the somethingHappened predicate to track whether or not  In computer programming, a callback, also known as a "call-after" function, is any executable code that is passed as an argument to other code; that other code is expected to call back (execute) the argument at a given time.

What is a callback method in java? Term seems to be used loosely , Remote operations are documented in terms of operation signatures: operation In the next section, we will see how these modes are used to meet different using the same software technology (e.g. Java Remote Method Invocation), are Conversely, interfaces that are loosely coupled, for example, those where the  37 What is a callback method in Java? (Term seems to be used loosely) (Term seems to be used loosely) 28 Function with SQL query has no destination for result data

Java Tip 10: Implement callback routines in Java, The configuration metadata is represented in XML, Java annotations, or Java code. The id attribute is a string that you use to identify the individual bean definition. Thus, although initialization lifecycle callback methods are called on all objects regardless of scope The corresponding bean definitions appear as follows. sorry i don't know what is the purpose of the callback URL in most SSO context. Could someone please give me some tips, like why is the callback URL necessary, what it is used for, and what should i do in the callback URL. Thank you.

OSS Design Patterns: A Pattern Approach to the Design of , Flexible: The library should support callbacks to functions, function objects, and Loosely Coupled: Libraries should be independent of client code. Callbacks are most easily described in terms of the telephone system. patterns since it shows the details of how each pattern was applied and how each  Use of callback objects in Java applets is limited due to Java applet security mechanisms. Any Java applet run-time environment that allows a Java applet to create and listen on sockets (via the proprietary environment or protocol of the Java applet) can act as a joint client/server application.

Comments
  • This is a fine example, I would like to add the following: a callback method can be any method in any class; a reference to an instance of the class is maintained in some other class, and, when some event happens in that other class, it calls the method from the first class. The only thing that makes it a callback as distinguished from any other method call is the idea of handing a reference to an object for the purpose of having that object invoke a method on it later, usually on some event.
  • Sorry I am new to java. Could this be done without an anonymous class? Does it have to be Callback interface? Can you provide a different example that doesn't use Callback interface if there is a way to do it without using this Callback interface?
  • @ImtiazAhmad No, the anonymous class is to make the example shorter. You could create a public class MyCallbackImpl implements Callback.
  • @ImtiazAhmad Without the callback, the code inside the anonymous class would need to be called directly in the doWork() method.
  • How would it be called directly in doWork() method?