天天看點

關于回調的一個最簡單的Demo

示範執行個體:學生提問問題後,通過回調方法,展示出老師的回答

1、回調接口

public interface CallBack {
	
	public void answer(String result);
}
           

2、學生類

public class Student implements CallBack{
	
	private Teacher mTeacher;
	
	public Student(Teacher mTeacher){
		this.mTeacher = mTeacher;		
	}
	
	public void ask(int a, int b){
		System.out.println("學生發出提問:"+ a +"+"+ b +"=?");
		mTeacher.reply(Student.this, a, b);
	}

	@Override
    public void answer(String result) {
	    System.out.println("老師公布的答案是——>"+ result);
    }

}
           

3、老師類

public class Teacher {

	public void reply(CallBack cb, int a, int b){
		System.out.println("老師收到學生的提問——>"+ a +"+"+ b +"=?");		
		cb.answer(String.valueOf(a+b));
	}
}
           

4、執行類

public class Test {

	public static void main(String[] args) {
		Teacher teacher = new Teacher();
	    Student student = new Student(teacher);
		student.ask(3,5);	    
    }
}