2025-02-10

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、常量接口(這裡不在講)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *