一、java的接口定义以及向上转型是理解回调的基础;java
使用接口的核心缘由:为了可以向上转型为多个基类型。即利用接口的多实现,可向上转型为多个接口基类型。ide
二、匿名类。函数
代码随处可见new SthInterface()注册接口回调。测试
感谢csdn两篇文章让我完全理解回调函数:this
其实我很愿意理解网上那个关于打电话需求帮助的回调函数例子spa
在此我也写了一个与此相似的例子:code
一、首先定义一个接口(即回调接口)(帮助接口,能够向张三需求帮助,也能够向李四需求帮助,具体须要什么帮助,后期绑定本身实现。)orm
public interface HelperInterface { void execute(); }
二、咱们可让张三帮助咱们解决问题(固然找李四或者王五等)接口
public class HelperZhangsan implements HelperInterface{ @Override public void execute() { System.out.println(This is zhangsan_helper.You can also ask lisi_helper!!); } }
三、寻求帮助的类,他必须持有帮助的回调接口,由于找不到张三,能够找李四,只要回调接口不变,总能够找到帮助的类。回调函数
public class Ask { private HelperInterface helperInterface; public void setHelperInterface(HelperInterface helperInterface){ //注册 this.helperInterface = helperInterface; } public void resultForAsk(){ helperInterface.execute(); } }
四、测试代码类
public class Test { public static void main(String[] args) { Ask ask = new Ask(); ask.setHelperInterface(new HelperZhangsan()); ask.resultForAsk(); } }
其实不少时候咱们更愿意以下这种写法,也即找个匿名接口实现类帮助咱们():
public class Test { public static void main(String[] args) { Ask ask = new Ask(); ask.setHelperInterface(new HelperInterface() { @Override public void execute() { System.out.println(hell dsc); } }); ask.resultForAsk(); } }
以上就是完整的回调函数的工做机制。