Here I am showing a simple example on what is callback method in Java. A callback is a piece of code that you can pass as an argument to be executed on some other code. Since Java doesn’t yet support function pointer, the callback methods are implemented as command objects.

A callback will usually hold reference to some state to which it actually becomes useful.

By making the callback implementation in your code, you gain indirection between your code and the code that is executing the callback.

So, 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 an event happens in 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 handling a reference to an object for the purpose of having that object invokes a method on it later, usually on some events.

Let’s say you are calling a method from another method, but the key is that the callback is treated like an Object, so you can change which method to call based on the state of the system (like the Strategy Design Pattern).

Example

My own Callable interface.

package com.roytuts.java.callback.method;

interface Callable {

	void call();

}

Worker class who calls the callback.

package com.roytuts.java.callback.method;

public class Worker {

	public void doWork(Callable callable) {
		System.out.println("Doing Work");
		callable.call();
	}

}
package com.roytuts.java.callback.method;

public class CallBackMethodApp {

	public static void main(String[] args) {

		new Worker().doWork(new Callable() {
			@Override
			public void call() {
				System.out.println("Callback Called");
			}
		});

	}

}

Executing the above main class will give you the following output:

Doing Work
Callback Called

Source Code

Download

Thanks for reading.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *