Reference: Think in Java
// Define an Interface
Interface incrementable ...{
Void increment ();
}
// A simple interface implementation class
Class callee1 implements incrementable ...{
Private int I = 0;
Public void increment ()...{
I ++;
System. Out. println (I );
}
}
Class myincrement ...{
Void increment ()...{
System. Out. println ("other operator ");
}
Static void F (myincrement mi)
...{
Mi. increment ();
}
}
// Callee2 wants to change the increment () method behavior in myincrement.
// It is mainly because callee2 has a completely different incr () method.
// The problem to be solved is to call the incr method when calling the increment method.
// The parent class has an increment, which cannot be overwritten by the usage of the word class.
// Therefore, the word class re-writes an incr method.
Class callee2 extends myincrement ...{
Private int I = 0;
// A method used to replace the incrment method.
Private void incr ()...{
I ++;
System. Out. println (I );
}
// Internal class implementation incrementable Interface
Private class closure implements incrementable ...{
Public void increment ()...{
Incr ();
}
}
// Get a callback reference
Incrementable getcallbackreference ()...{
Return new closure ();
}
}
Class caller ...{
Private incrementable callbackreferences;
// It only needs one interface.
Caller (incrementable CHB )...{
Callbackreferences = CHB;
}
Void go ()...{
Callbackreferences. increment ();
}
}
Class callbacks ...{
Public static void main (string [] ARGs )...{
Callee1 C1 = new callee1 ();
Callee2 C2 = new callee2 ();
Myincrement. F (C2 );
Caller caller1 = new caller (C1 );
// The client does not know the implementation of the incrment method in caller2.
// In fact, callee2 completely changes the incrment method (another method is called)
Caller caller2 = new caller (c2.getcallbackreference ());
Caller1.go ();
Caller1.go ();
Caller2.go ();
Caller2.go ();
}
}
// The value of callback lies in its flexibility. It determines the method to call at runtime.