java的接口回调原理网上已经有很多生动形象的例子说明了,在此总结一下个人的理解:类A调用类B的方法b(),类B再回调类A的方法a(),其中方法a()是定义在接口中的,由类A来实现。这是一个双向调用的过程,用下面的类图来加以说明。
Callback.png
1. 创建一个接口:
public interface CallBack{
public void finish(String result);
}
接口定义了一个回调方法finish(),由类Manager实现,供类Employee回调。
2. 创建Manager类实现上面的接口
public class Manager implements CallBack{
private Employee employee;
public Manager(Employee employee){
this.employee = employee;
}
public void assign(){
System.out.println("to finish this work");
employee.get(Manager.this);
}
public void finish(String result){
System.out.println("well done..." + result);