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".
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")); } }
Event Occurred Callback Invoked
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions