回调的概念

来源:互联网 发布:java shiro demo 编辑:程序博客网 时间:2024/06/04 19:59

回调

1、接口回调

接口实例化,然后回调声明过的函数

interface People{   void peopleList();  //回调函数}class Student implements People{   public void peopleList(){    System.out.println("I’m a student.");}}class Teacher implements People{  public void peopleList(){    System.out.println("I’m a teacher.");}}public class Example{ public static void main(String args[]){ People a;             //声明接口变量 a=new Student();      //实例化,接口变量中存放对象的引用 a.peopleList();        //接口回调 a=new Teacher();     //实例化,接口变量中存放对象的引用 a.peopleList();       //接口回调}}

android接口回调

常采用内部类的实现方式(实现将方法以参数的形式传递)

1.定义接口  public interface OnClickListener {      public void OnClick(Button b);  }  2. 定义Button  public class Button {    OnClickListener listener;    public void click() {      listener.OnClick(this);    }    public void setOnClickListener(OnClickListener listener) {      this.listener = listener;    }  }  3. 将接口对象OnClickListener 赋给 Button的接口成员  public class Activity {    public Activity() {    }    public static void main(String[] args) {      Button button = new Button();   '   button.setOnClickListener(new OnClickListener(){  '       @Override   '       public void OnClick(Button b) {               ' '                System.out.println("clicked");       '       }         });      button.click(); //user click,System call button.click();    }  }  
0 0
原创粉丝点击