?
5进制空间,转载请注明出处,谢谢。
常用用法:回调方法接口,向上转型动态绑定,常量接口。
回调方法接口:
?
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("dosth"); } }); caller.doCallback(); }}
?
向上转型:
?
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; //声明接口变量a=new Student(); //实例化,接口变量中存放对象的引用a.peopleList(); //接口回调a=new Teacher(); //实例化,接口变量中存放对象的引用a.peopleList(); //接口回调}}结果:I’m a student.I’m a teacher.
?
?
?
常量接口就不举例了。举个回调接口在 Android中的例子。
实例(对于Android界面上Button点击事件监听的模拟):
1.定义接口
?
?
public interface OnClickListener { public void OnClick(Button b);}?
?
?
2. 定义Button
public class Button { OnClickListener listener; public void click() { listener.OnClick(this); } public void setOnClickListener(OnClickListener listener) { this.listener = listener; }}
?
3. 将接口对象OnClickListener 赋给 Button的接口成员
public class MyActivity extends Activity{ Button button = new Button(); button.setOnClickListener(new OnClickListener(){ public void OnClick(Button b) { System.out.println("clicked"); } }); }}?
5进制空间,转载请注明出处,谢谢。