Search on the Internet many articles about the Java callback function, I have to try to write this blog, there may be some places do not understand the place, please make a big correction.
In computer programming, a callback function , or callback, refers to a piece of executable code that passes through a function parameter to another code. This design allows the underlying code to invoke subroutines defined at the top level.
In Java, we use interfaces to implement callbacks.
Simulate a scene: A girl calls her boyfriend man, and then man replies to her:
First define an interface:
Package Mine.callback2;public interface Callinterface {void execute ();}
Girl:
Package Mine.callback2;public class Girl {public callinterface ci;//save an interface reference public void Setcallfun (Callinterface ci) { This.ci=ci;} public void Call () {ci.execute ();//callback Implements Callinterface interface in Man's Method}}
Mans:
Package Mine.callback2;public class Man implements Callinterface {@Overridepublic void execute () {System.out.println (" Yes, the Queen "); public static void Main (string[] args) {Girl Girl = new Girl (), Girl.setcallfun (New Man ()); Girl.call ();}}
The interface is unchanged, implementing the same functionality as:
Girl:
Package Mine.callback1;public class Girl {public callinterface ci;public void Callfun (Callinterface ci) { System.out.println ("Accompany me to go shopping, OK?"); Ci.execute ();//Callback Operation}}
Mans:
Package Mine.callback1;public class Mans {public static void Answera () {System.out.println ("Good, Queen!");} public static void Answerb () {System.out.println ("Sorry, I still have a task to finish here, I have time to accompany you later."); public static void Main (string[] args) {Girl Girl = new Girl (); Girl. Callfun (New Callinterface () {@Overridepublic void execute () {//here can call more answers Answerb ();}});}}
If the idea is not clear enough to see this article: http://kidult.iteye.com/blog/148982
Java callback Comprehension (step by step)