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?
Interface variables are static because java interfaces cannot be instantiated on their own. 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.
1) An interface can contain following type of members. ....public, static, final fields (i.e., constants) .... default and static methods with bodies 2) An instance of interface can be created. 3) A class can implement multiple interfaces. 4) Many classes can implement the same interface.
In Java syntactically it is possible and allowed to define constants in both Interface and Class. In old days putting constants in Interface was common practice because by default defined constants are marked public static final and constants can be used in implementation class without interface name prefix.
Yes the public is redundant, because in an Interface all methods are implictly public and abstract . I think its is a bad style to add public , or abstract , because both are implicitly applied. Every method declaration in the body of an interface is implicitly public (§6.6).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With