简体   繁体   中英

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 ?

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.

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

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). 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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