Java接口中的方法并非没有修饰符,而是省略了。在Java的接口中,只有常量和抽象方法。所有的数据域均用 public static final 修饰,所有的方法都用 public abstract 修饰,所以修饰符是可以省略的。
我刚才看了下官方文档,在 Java 8 中,接口中可以定义默认方法和静态方法了。
以下是部分内容:
The Interface Body
The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). Default methods are defined with the default modifier, and static methods with the static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the public modifier.
In addition, an interface can contain constant declarations. All constant values defined in an interface are implicitly public, static, and final. Once again, you can omit these modifiers.
------ 2017.02.10 ------
在阿里巴巴技术团队2017.02.09发布的《阿里巴巴Java 开发手册》中也有提到接口规约,如下:
12. 【推荐】接口类中的方法和属性不要加任何修饰符号( public 也不要加) ,保持代码的简洁性,并加上有效的 Javadoc 注释。尽量不要在接口里定义变量,如果一定要定义变量,肯定是与接口方法相关,并且是整个应用的基础常量。
正例: 接口方法签名: void f();
接口基础常量表示: String COMPANY = "alibaba";
反例: 接口方法定义: public abstract void f();
说明: JDK8 中接口允许有默认实现,那么这个 default 方法,是对所有实现类都有价值的默认实现。