java接口修饰符省略_Java 接口中方法为什么没有修饰符?

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 方法,是对所有实现类都有价值的默认实现。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值