Interfaces for Callback Mechanisms in Java


Create a Java program to demonstrate the use of an interface to implement a simple callback mechanism

The lambda expression () -> System.out.println("Callback Invoked") represents the implementation of the onCallback() method. When registerCallback() is called, the lambda expression is passed as an argument, and the event listener invokes the callback by calling its onCallback() method. As a result, "Event Occurred" is printed first, followed by "Callback Invoked".

Source Code

interface Callback
{
	void onCallback();
}
 
class EventListener
{
	void registerCallback(Callback callback)
	{
		// Some event occurs
		System.out.println("Event Occurred");
		callback.onCallback();
	}
}
 
public class Main
{
	public static void main(String[] args)
	{
		EventListener listener = new EventListener();
		listener.registerCallback(() -> System.out.println("Callback Invoked"));
	}
}

Output

Event Occurred
Callback Invoked

Example Programs