I came across this question about callbacks in Java. Hers is the running code and original answer here.
- But I didn’t understand how is it useful for callback?
- Can you explain the concept of callback to a Java programmer?
Code:
public class Main {
public interface Visitor {
int DoJob(int a, int b);
}
public static void main(String[] args) {
Visitor adder = new Visitor(){
public int DoJob(int a, int b) {
return a + b;
}
};
Visitor multiplier = new Visitor(){
public int DoJob(int a, int b) {
return a*b;
}
};
System.out.println(adder.DoJob(10, 20));
System.out.println(multiplier.DoJob(10, 20));
}
}
I wrote a small blog post on this sometime back : http://madhurtanwani.blogspot.com/2010/09/callbacks-in-java.html. Hope it helps!
Before I try explaining the above code post, I must say, its not the most intuitive or good use of call backs. The example I’ve used in my post is of Collections.sort() which clearly brings out the callback part.
Neverthelss, for the code posted above, think of like this :
doJobmethod on aVisitorinterfaceimplementations, whenever I receive a pair of data sets. What the caller must do is implement the Visitor interface and implement the domain specific logic to process the datasets.The part of delegating processing from the caller, back to the callee is called a callback implemented using
interface(contract specification) in Java.