常用用法:回调方法接口,向上转型动态绑定,常量接口。
回调方法接口:
Java代码
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();
}
}
=========================================================================
向上转型:
Java代码
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.定义接口
Java代码
public interface OnClickListener {
public void OnClick(Button b);
}
2. 定义Button
Java代码
public class Button {
OnClickListener listener;
public void click() {
listener.OnClick(this);
}
public void setOnClickListener(OnClickListener listener) {
this.listener = listener;
}
}
3. 将接口对象OnClickListener 赋给Button的接口成员
Java代码
public class MyActivity extends Activity{
Button button = new Button();
button.setOnClickListener(new OnClickListener(){
public void OnClick(Button b) {
System.out.println("clicked");
} });
}
}