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?
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.
Interface : System requirement service.
In interface, variable are by default assign by public,static,final access modifier. Because :
public : It happen some-times that interface might placed in some other package. So it need to access the variable from anywhere in project.
static : As such incomplete class can not create object. So in project we need to access the variable without object so we can access with the help of
interface_filename.variable_name
final : Suppose one interface implements by many class and all classes try to access and update the interface variable. So it leads to inconsistent of changing data and affect every other class. So it need to declare access modifier with final.
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)
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.
Interface variables are always static and final.