Reprint: http://wangyang0311.iteye.com/blog/368031
In general, it is divided into the following steps:
- The unified interface for declaring a callback function is interface A, which contains the method callback ();
- The interface is set to private members within the calling class caller.
- The public method for implementing the A interface is provided within the caller (the implementation class of the external interface is passed through the formal parameter to the caller XXX);
- The Xxx.callback () method is used in a caller method Dosth ();
- In the example of caller, a interface is implemented first, then the Dosth () method is called.
Popular Online Code:
//callback function interface and method Public InterfaceIcallback { Public voidfunc (); }//callback function interface implementation class Public classClasswithcallbackfunctionImplementsicallback{ Publicclasswithcallbackfunction () {} Public voidfunc () {System.out.println ("CCCCCCCCCCCCCCCCCC"); }} Public classCaller {PrivateIcallback callback;//Private Interface Members Public voidSetcallback (Icallback callback) { This. callback = callback;//implementation of interface members: incoming from outside } Public voidDoCallback () {//methods for callback interface membersCallback.func (); } }} Public classMainClass { PublicMainClass () {} Public Static voidMain (string[] args) {Caller Caller=NewCaller (); Caller.setcallback (Newclasswithcallbackfunction () { Public voidfunc () {System.out.println ("Aaaaaaaaaa"); } }); Caller.docallback (); //Implementing Callbacks }} //In Reality, the DoCallback () method is placed in the Setcallback call, the above is to illustrate the callback principle Public classCaller {Icallback callback; Public voidDoCallback () {callback.func (); } Public voidSetcallback (Icallback callback) { This. Callback =callback; DoCallback (); }}
Java Sort Interface
InterfaceCompare {BooleanLessThan (Object LHS, object RHS); Booleanlessthanorequal (Object LHS, object RHS); }ImportJava.util.*; Public classSortvectorextendsVector {PrivateCompare Compare;//Private Interface Members PublicSortvector (Compare comp) {Compare=comp; } Public voidsort () {QuickSort (0, size ()-1); }Private voidQuickSort (intLeftintRight ) {if(Right >Left ) {Object O1=ElementAt (right); inti = left-1; intj =Right ; while(true) { while(Compare.lessthan (ElementAt (++i), O1)); while(J > 0)if(Compare.lessthanorequal (ElementAt (--j), O1)) Break; if(I >= J) Break; Swap (I, j); } swap (I, right); QuickSort (left, I-1); QuickSort (i+1, right); }}Private voidSwapintLoc1,intloc2) {Object tmp=ElementAt (LOC1); Setelementat (ElementAt (LOC2), Loc1); Setelementat (TMP, LOC2); }}
Java Learning notes-callback functions