Android中定義介面的用法

來源:互聯網
上載者:User

1、介面方法用於回調(這裡定義介面是為了使用其介面方法):
 
01
public interface ICallback {
02
  public void   func();
03
}
04
  
05
public class Caller {
06
  ICallback callback;
07
  public void doCallback() {
08
    callback.func();
09
  }
10
  
11
  public void setCallback(ICallback callback) {
12
    this.callback = callback;
13
  }
14
  
15
}
16
  
17
public class MainClass {
18
  public MainClass() {
19
  }
20
  
21
  public static void main(String[] args) {
22
    Caller caller = new Caller();
23
    caller.setCallback(new ICallback () {
24
      public void func() {
25
        System.out.println("dosth");
26
      }
27
    });
28
    caller.doCallback();
29
  }
30
}
2、向上轉型
 
01
interface People{
02
   void peopleList();
03
}
04
class Student implements People{
05
   public void peopleList(){
06
       System.out.println("I’m a student.");
07
  }
08
}
09
class Teacher implements People{
10
   public void peopleList(){
11
       System.out.println("I’m a teacher.");
12
   }
13
}
14
public class Example{
15
   public static void main(String args[]){
16
       People a;             //聲明介面變數
17
       a=new Student();      //執行個體化,介面變數中存放對象的引用
18
       a.peopleList();        //介面回調
19
       a=new Teacher();     //執行個體化,介面變數中存放對象的引用
20
       a.peopleList();       //介面回調
21
  }
22
}
23
運行結果:
24
I’m a student.
25
I’m a teacher.
3、常量介面(這裡不在講)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.