原理就不讲了,这里只记录几种写法的demo:

1. interface,回调函数在A里实现

A.java

public class A {

public static void main(String[] args) {
B b = new B();
b.setBListener(new IB() {
@Override
public void onSuccess(String message) {
System.out.println("A里定义onSuccess,meesage="+message);
}

@Override
public void onError(String error) {
System.out.println("A里定义onError,error="+error);
}
});
b.start(true);
b.start(false);
}

}

IB.java

public interface IB{
public void onError(String error);
public void onSuccess(String message);
}

B.java

public class B  {
private IB b;

public void setBListener(IB b) {
this.b = b;
}

public void start(boolean input){
if(input)
b.onSuccess("YES");
else
b.onError("NO");
}
}

2. interface的一般用法,不是回调

A.java

public class A {

public static void main(String[] args) {
B b = new BImpl();
b.onSuccess("A里调用onSuccess");
b.onError("A里调用onError");
}
}

B.java

public interface B{
void onError(String error);
void onSuccess(String message);
}

BImpl.java

public class BImpl implements B{

@Override
public void onError(String error) {
System.out.println("运行B里定义的onError,打印参数:" + error);
}

@Override
public void onSuccess(String message) {
System.out.println("运行B里定义的onSuccess,打印参数:" + message);

}
}

3. abstract

A.java

public class A {

public static void main(String[] args) {

B b = new B();
b.start(new Callback() {
@Override
public void success(String message) {
System.out.println("定义在A里的 success,参数值:" + message);
//super.success(message);
}

@Override
public void error(String err) {
System.out.println("定义在A里的 error,参数值:" + err);
//super.error(err);
}
});
}

}

B.java

public class B{
public void start(final Callback callback) {
callback.success("YES");
callback.error("NO");
}
}

Callback.java

public abstract class Callback {
public void success(String successMsg) {}
public void error(String exceptionMsg) {}
}