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()」变成预设方法。