2017年11月2日 星期四

Day1-4 - 宣告介面

1.1 Develop code that declares classes (including abstract and all forms of nested
classes), interfaces, and enums, and includes the appropriate use of package and import
statements (including static imports).

1.2 Develop code that declares an interface. Develop code that implements or extends
one or more interfaces. Develop code that declares an abstract class. Develop code that
extends an abstract class.


宣告介面 (declare interface)

- 一份介面interface,就是一份合約contract
- 這個合約定義那些功能需要做,但不需要說明如何做
- interface可以存在在任何一顆inheritance tree(繼承樹)內,或被任何class implement。 (ex: 人
和樹都有高度Height,但人和樹並沒有共享任何繼承關係。藉由同時實作Height interface,說明人和樹都有高度這樣的東西,對於Java就是可以呼叫高度內的功能
- implement此interface時,皆需要implement所有interface的method且必須為public
- interface為一百分之百的abstract class
- 假設A implements interface IT,B extends A implements IT 是正確,且B不需要再實作一次IT

abstract void bounce(); //記住interface需要以分號結尾

interface和abstract的差別:
  1.  interface內可以同時定義abstract & non abstract method,interface只能定義abstract method
  2.  interface宣告method和variable的規則嚴格
interface的宣告限制:
  • interface method隱含為public & abstract (不需要特別定義,因為一定是)(另外因為interface就是定義為what you can see from outside the class,所以一定是public)
  • interface 也一定要是public
  • interface variable必須是public, static, final,意即interface只能宣告常數,不能宣告instance variable. 因為interface無法實體化,所以class在實作此interface的時候就可以直接使用constant,而且保證是不會變的值(final)。  Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.- Java interface design FAQ by Philip Shaw
  • interface method不能是static(介面內只能定義實體函式instance methods)
  • interface method因為是abstract,所以不能被標註final, strictfp, native
  • interface可以extends其他interface(注意不是implements)
  • interface不能extends class or other abstract class
  • Class extends class and Interface extends interface 這兩句話是正確的
  • interface不能implement其他的interface or class
  • interface的identifier為interface
  • interface可以被philosophically使用
  • interface可以的signature可以是default或public,但裡面的method一定只能是public&abstract
  • implement interface的時候,不可以宣告新的checked exception ex: public String generate() throws FileNotFoundException 但可以加入RuntimeException
  • implement interface的時候,signature需要一樣,但不需要宣告interface上的exception

以下五種情況都是legal且相同

void bounce();

public void bounce();

abstract void bounce();

public abstract void bounce();

abstract public void bounce();//順序不限

宣告介面常數 (declare interface constant)

- 將常數放入interface,可以保證implement此interface的class能夠直接存取constant,就像直接extends一樣
- interface constant一定是 public static final (所以不需要特別用modifier宣告),而且不能被任何class修改

以下表達意義皆相同

public int x = 1;

int x = 1;

static int x = 1;
final int x = 1; 
public static int x = 1; 
public final int x = 1; 
static final int x = 1;
public static final int x = 1; // 所有上面的值都暗指此

沒有留言:

張貼留言