Is “public static final” redundant for a constant in a Java interface?

允我心安 提交于 2019-12-18 12:07:19

问题


This code:

interface Config {
    int MAX_CONN = 20;
}

compiled and worked as I expected. It looks like this is the same as:

interface Config {
    public static final int MAX_CONN = 20;
}

Is "public static final" redundant for a constant in a Java interface? Is this true for Java 1.1, 1.2, 1.3, 1.4,..., 1.8 or did it change in a Java release?


回答1:


Variables declared in Interface are implicitly public static final. This is what JLS 9.3 says :

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.

Read through the JLS to get an idea why this was done.

Look at this SO answer:

Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.




回答2:


Interface variables are implicitly static and final because Java interfaces cannot be instantiated on their own.

Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

http://en.wikipedia.org/wiki/Interface_(Java)




回答3:


Interface variables are static because Java interfaces cannot be instantiated in their own right. Value of the variable must be assigned in a static context - no instance exists. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.




回答4:


Interface variables are always static and final.




回答5:


If the interface has to be refactored to a class, it may be more practical to keep the redundant public static final, though. (This sounds odd, because each IDE flags those as redundant information).

EDIT To be fair: One would not do this without changing lots of other places (as interfaces are using implements, while inheriting from classes use extends)

EDIT#2 In fact, constant interface(s) can be considered to be an anti-pattern, please see on wikipedia - Constant Interface



来源:https://stackoverflow.com/questions/17592872/is-public-static-final-redundant-for-a-constant-in-a-java-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!