简体   繁体   English

为什么接口有字段而且它们是公开的?

[英]Why interface has fields and they're public?

I understand those fields are public static final by default, my question is on why it's public ?我知道默认情况下这些字段是public static final的,我的问题是为什么它是public

I think my question comes from why interface has fields.我想我的问题来自为什么接口有字段。 Strangely I read from other answers on this site and accepted that they're static final , but why public is confusing for me.奇怪的是,我从本网站上的其他答案中阅读并接受了它们是static final ,但为什么public对我来说很困惑。

Interfaces are meant to be implemented by other classes, not to encapsulate any data.接口旨在由其他类实现,而不是封装任何数据。 This is why all fields are public.这就是为什么所有字段都是公开的。

Relevant bit of spec: https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.3相关规范: https : //docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.3

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.允许为此类字段冗余指定任何或所有这些修饰符。

You are only allowed to redundantly affirm that you want public, trying to change it results in a compile-time error.您只能重复确认您想要公开,尝试更改它会导致编译时错误。

Private would be almost completely pointless (the implementing class would not be able to see the field). Private 几乎完全没有意义(实现类将无法看到该字段)。 If you say nothing you get public instead of the usual "package" visibility.如果你什么都不说,你就会公开而不是通常的“包”可见性。 And you are prevented from specifying protected.并且您无法指定受保护。 Not sure if there is a valid use-case for wanting that.不确定是否有想要的有效用例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM