Tuesday, May 29, 2012

How to Use Java Callbacks ?


1-Open your Java file in an editor such as Eclipse, Netbeans or JBuilder X.
2-Create an interface and two classes that implement the interface by adding the following code above your main function:
interface Fruit {
void callback_method();
}
class Apple implements Fruit {
public void callback_method() {
System.out.println("Callback - Apple");
}
}
class Banana implements Fruit {
public void callback_method() {
System.out.println("Callback - Banana");
}
}
Each class that implements the interface must have a version of the method defined in the interface.
3-Create a "caller" class that has a method to initiate the callback by adding the code:
class Caller {
public register(Fruit fruit) {
fruit.callback_method();
}
}
In the example, the "register" method can take either an "Apple" or "Banana" as its input and then execute the matching "callback_method" for that version.
4-Create "Caller", "Apple" and "Banana" objects and then pass both versions of the "Fruit" to the "Caller" object's "register" method, by adding the following code as your main function:
public static void main(String[] args) {
Caller caller = new Caller();
Fruit apple = new Apple(); // Apple version of Fruit
Fruit banana = new Banana(); // Banana version of Fruit
caller.register(apple); // displays "Callback - Apple"
caller.register(banana); // displays "Callback - Banana"
}
This lets you avoid having to create multiple versions of the "Caller" class for each implementation. Any implementation of "Fruit" can be passed to the "Caller," which loads the corresponding callback method for that version.
5-Save the Java file, compile and run the program to view the callbacks.

No comments:

Post a Comment