Which of the following can fill in the blank in this code to make it compile?



interface CanFly {

    String type = "A";

    void fly();

    ˍˍˍˍˍˍˍ  String getType() {
        return type;
    }
}

A. abstract
B. public
C. default
D. It will not compile with any as interfaces cannot have non abstract methods.
E. It will compile without filling the blank.

題解

這題是在考Java 8的新特性,也就是介面(interface)的預設(default)方法和靜態(static)方法。

若要在介面實作預設方法,需使用「default」修飾字來定義方法,預設方法只能由實作這個介面的類別所實體化出的物件來使用;若要在介面實作靜態方法,需使用「static」修飾字來定義方法,靜態方法只能透過介面來使用,無法透過實作這個介面的物件實體來使用。

因此在這個題目中,可以填入選項C的「default」,使「getType()」變成預設方法。