java接口不能有字段_Java Docs说接口不能有字段.为什么?

How could this be possible because Java Docs also says all fields in interface are public, static and final.

Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

If two or more (distinct) field modifiers appear in a field declaration, it is customary, though not required, that they appear in the order consistent with that shown above in the production for ConstantModifier.

这意味着界面中的每个字段都将被视为公共常量字段.如果你添加public,static和final或其中一些修饰符,或者没有添加它们,编译器会为你添加它们.这是含蓄的含义.

所以,有这个:

interface Foo {

String bar = "Hello World";

}

类似于

interface Foo {

public String bar = "Hello World";

}

这类似于

interface Foo {

static bar = "Hello World";

}

这三个接口将编译为相同的字节码.

另外,请确保接口中的字段声明遵循子注释.这意味着,您无法缩小界面中字段的可见性.这是非法的:

interface Foo {

//compiler error!

private String bar = "Hello World";

}

因为bar不是公共的,它违反了接口中字段的标准定义.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值