回调函数浅析(JAVA)语言

网上看了很多回调函数的浅析,作为入门级,写了一个带注释更便于理解的小程序:

public class A {

    public CInterface mc;//定义一个接口
    public void setinterface(CInterface mc){
        this.mc = mc;
    }
    public void call(){//调用接口里的方法
        int i = this.mc.method();
        System.out.println(i);
        int j = this.mc.method2();
        System.out.println(j);
    }
}
//约定好一个接口,在这个接口中又method,method2这2个方法
public interface CInterface {
    public int method();
    public int method2();
}
public class B implements CInterface {

    public int method(){//B继承了这个接口,要实现接口中的2个方法
        int i=10;
        return i;
    }
    public int method2(){
        int i = 20;
        return i;
    }
    public static void main(String[] args) {
        A a = new A();//定义一个类A
        a.setinterface(new B());//在B中,把B的方法告诉A,call A
        a.call();//A中执行的是method,method2这2个方法,相当于call bcak
        
    }

}

浅析:首先双方约定好一个接口。A中:

setinterface(CInterface mc)识别传入的方法
call()调用上面传入的方法里约定好的method,method2

总结:在B中声明A,把自己告诉A,A调用call就是调用了B中的那2个方法。

 
原文地址:https://www.cnblogs.com/happyacm/p/3853047.html