回调函数:
回调函数,简称回调,是指通过函数参数传递到其他代码的,某一块可执行代码的引用。
所谓的回调:
- 程序员A写了一段程序(程序a),其中预留有回调函数的接口,并封装好了该程序。
- 程序员B要让a程序调用自己的程序b中的一个方法,于是,他通过a中的接口回调自己b中的方法。
程序员A通过a()方法,得到接口实现类b对象的引用,然后就可以重写b对象的b()方法。从而使用b()方法。
例子:
//程序员A写了一段程序(程序a),其中a()方法预留有接口的引用,并封装了该程序。
public class A {
private CallBack callInterface;
public A(){
}
public void a(CallBack callInterface){
this.callInterface=callInterface;
}
public void call(){
callInterface.printName();
}
}
//接口
public interface CallBack {
public void printName();
}
//程序B为接口的实现类
public class B implements CallBack {
public void printName() {
System.out.println("This is the client printName method");
}
}
public class Test {
public static void main(String[] args) {
//a通过a()方法,得到接口实现类b对象的引用
A a=new A();
a.a(new B());
//a调用b对象的方法
a.call();
}
}
匿名内部类的写法:
public class Test {
public static void main(String[] args) {
//a通过a()方法,得到接口实现类b对象的引用,并重写B对象的方法
A a=new A();
a.a(new CallBack() {
public void printName() {
// TODO Auto-generated method stub
System.out.println("回调方法");
}
});
//a调用b对象的方法
a.call();
}
}