Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 319
gavenkoa Avatar asked Jul 11 '13 12:07

gavenkoa


People also ask

Why interface constants are public static final?

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.

CAN interface have public static final fields?

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.

Are static constants in an interface legal in Java?

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.

Why is public redundant in interface?

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


1 Answers

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.

like image 195
AllTooSir Avatar answered Sep 22 '22 06:09

AllTooSir