定义
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中,