Java学习之 回调机制

来源:互联网 发布:巴西统计年鉴数据库 编辑:程序博客网 时间:2024/05/20 07:18

所谓的回调,简言之就是先写的代码调用后写的代码。主要形式:1)接口调用自己实现类中的重写方法。
2)父类调子类的重写方法。

(为了方便通过匿名内部类来实现)具体例子:

//定义接口public interface demo{    public abstract show();}
//定义一个Animal类public class Animal{    public show(){        System.out.println("Animal");    }}
public class Test{    public void method1(interface inf){        inf.show();    }    public void method2(Animal anm){        anm.show();    }    public static void main(String[] args) {        Test t = new Test();        t.method1(new interface(){            @override            public show(){                System.out.println("被回调了");            }        });        t.method2(new Animal(){            @override            public show(){                System.out.println("被回调了");            }        });    }}

和大家一起学习交流!

0 0
原创粉丝点击