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 provide an example code of a java callback method with an explanation, it be a great help in my java learning journey?
Thank you in advance.
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.
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
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.
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 eventE
(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:
Example 2:
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:
With Callback: Here is an example with a callback, using jQuery's getJSON: