接口回调机制理解

本文介绍了Java中接口回调机制的概念及其应用场景,通过一个生动的类比解释了如何使用接口回调来实现对象间的通信。在Android开发中,这种机制常见于Activity与OnClickListener的交互,当Button被点击时,回调接口使得Activity能够得知并作出响应。
摘要由CSDN通过智能技术生成

定义

Java允许调用接口的方法,但前提是编译时接口的对象必须是一个具体的类,并且实现了接口。
当我们调用接口时,接口的具体子类的具体方法会被调用,这就是回调。

public interface Interface {

void printClassName();

}

public class A implements Interface {

B b = new B();

b.setListener(this);

@Override
public void printClassName() {

    System.out.println("This is class A!请告诉我时间");
}

}

public class B {

Interface mInterface;

public void setListener(Interface interface){

    this.mInterface = interface;
}

// B 在setListener里面接受到Interface后的某个时刻,执行showPrint
public void showPrint(){

    if(mInterface != null){
        mInterface.printClassName();
    }
}

}


接口回调应用场景:

A:A
B:中间人B
C:C
A new 一个中间人B,并告诉B:如果C想吃饭了就立刻告诉A;
B再注册到C中,

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值