9.接口-java筆記

1.抽象類
抽象是普通類和接口之間的中庸之道。
接口所有的方法都沒有方法體。抽象類有些方法是抽象的,無方法體,有些是有方法體的。
但是抽象類和接口都不能實例化,都是繼承用的。
如果一個抽象類被繼承,其抽象應當被實現,否則導出類也是抽象類。
抽象類裏可以沒有抽象方法,abstract可以是該類無法實例化。
2.接口
可以有域,但默認都是static,final
方法都沒方法體,且自動都是public,所以實現一個接口,接口中定義的方法都必須定義爲public。
interface Instrument {
  // Compile-time constant:
  int VALUE = 5; // static & final
  // Cannot have method definitions:
  void play(Note n); // Automatically public
  void adjust();
}
使用接口的核心原因:可以依次向轉型爲每一個接口。其次是防止被實例化。
選抽象類還是選接口?如果創建不帶任何方法和域的基類時,選接口。如果某事物要成爲基類第一選擇是接口。
3.接口中方法名
如果接口和其他基類中有相同的方法,那麼只要能找到該方法定義就合法。
儘量避免這種情況。
4.擴展接口
interface Monster{ void menace();}
interface DangerousMonster extends Monster(){void destroy();}
5.接口中的域
由於域是static final所以只有一份,且在用之前一定得被初始化。
6.爲什麼要用接口構建諸如工廠之類的模式? 原因是想要創建框架,框架是通用的。下面有代碼可以參考。
nterface Service {
  void method1();
  void method2();
}

interface ServiceFactory {
  Service getService();
}

class Implementation1 implements Service {
  Implementation1() {} // Package access
  public void method1() {print("Implementation1 method1");}
  public void method2() {print("Implementation1 method2");}
}   

class Implementation1Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation1();
  }
}

class Implementation2 implements Service {
  Implementation2() {} // Package access
  public void method1() {print("Implementation2 method1");}
  public void method2() {print("Implementation2 method2");}
}

class Implementation2Factory implements ServiceFactory {
  public Service getService() {
    return new Implementation2();
  }
}   

public class Factories {
  public static void serviceConsumer(ServiceFactory fact) {
    Service s = fact.getService();
    s.method1();
    s.method2();
  }
  public static void main(String[] args) {
    serviceConsumer(new Implementation1Factory());
    // Implementations are completely interchangeable:
    serviceConsumer(new Implementation2Factory());
  }
} /* Output:
Implementation1 method1
Implementation1 method2
Implementation2 method1
Implementation2 method2
*///:~




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章