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

gavenkoa picture gavenkoa · Jul 11, 2013 · Viewed 30.4k times · Source

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?

Answer

NINCOMPOOP picture NINCOMPOOP · Jul 11, 2013

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.