Common usage: callback method interface, dynamic binding to upward transformation, constant interface.
Callback method interface:
Java code
Public interface ICallback {
Public void func ();
}
Public class Caller {
ICallback callback;
Public void doCallback (){
Callback. func ();
}
Public void setCallback (ICallback callback ){
This. callback = callback;
}
}
Public class MainClass {
Public MainClass (){
}
Public static void main (String [] args ){
Caller caller = new Caller ();
Caller. setCallback (new ICallback (){
Public void func (){
System. out. println ("dosomething ");
}
});
Caller. doCallback ();
}
}
Upward Transformation:
Java code
Interface People {
Void peopleList ();
}
Class Student implements People {
Public void peopleList (){
System. out. println ("I'm a student .");
}
}
Class Teacher implements People {
Public void peopleList (){
System. out. println ("I'm a teacher .");
}
}
Public class Example {
Public static void main (String args []) {
People a; // declare interface Variables
A = new Student (); // instantiation, where the interface variable stores object references
A. peopleList (); // interface callback
A = new Teacher (); // instantiate, the interface variable stores the object reference
A. peopleList (); // interface callback
}
}
Result:
I'm a student.
I'm a teacher.
The constant interface is not used as an example. Here is an example of a callback interface in Android.
Instance (simulate a Button click event listener on the Android Interface ):
1. Define the interface
Java code
Public interface OnClickListener {
Public void OnClick (Button B );
}
2. Define the Button
Java code
Public class Button {
OnClickListener listener;
Public void click (){
Listener. OnClick (this );
}
Public void setOnClickListener (OnClickListener listener ){
This. listener = listener;
}
}
3. Assign the OnClickListener interface object to the interface member of the Button.
Java code
Public class MyActivity extends Activity {
Button button = new Button ();
Button. setOnClickListener (new OnClickListener (){
Public void OnClick (Button B ){
System. out. println ("clicked ");
}
});
}
}
5-digit space,