發新話題

Java 教程《語法說明》定義 Interface

Java 教程《語法說明》定義 Interface

■ 定義 Interface
[Interface-Modifiers] interface InterfaceName extends InterfaceList{
  /* Abstract methods and class constants etc. declared here */
  ConstantDeclaration
  AbstractMethodDeclaration
  ClassDeclaration
  InterfaceDeclaration

}
[註] InterfaceList 指的是以逗號隔開的多個 interfaces 。

[說明]
1. interface 是一個介面,只宣告 method,卻不定義 method 的內容。
 亦即 interface 所包含的函式必須全部都是僅宣告,而不實作程式碼的函式(預設都是抽像函式);
 而抽像類別內允許包含實作程式碼的函式,但至少有一個是僅宣告但未實作程式碼的 method(指必須至少有一個 abstract method)。
2. interface 內的 method 自動變成 public 和 abstract
3. interface 內宣告的變數都是公開常數型態,亦即所有變數都如同使用『public』、『static』和『final』修飾字,且該變數必須有初值的設定。
4. 介面允許繼承多重介面。

[限制]
1. 宣告在 interface 內的 method 不能有任何的實作(implementation),也不能宣告為 private、protected、static、final、或 synchronized。
2. 宣告在 interface 內的 instance variable 被認定為常數。不能宣告為 private、protected、或 synchronized。

[範例]
public interface Looptest {
  int MAX = 10;  // 定義常數
  void loopMethod( );   // 宣告 method
}

TOP

發新話題

本站所有圖文均屬網友發表,僅代表作者的觀點與本站無關,如有侵權請通知版主會盡快刪除。