ramgorur
ramgorur

Reputation: 2164

why compiler says a public static field in interface is "final" although it is not

Please see the below code --

public interface TestInterface {
    public static String NON_CONST_B = "" ; 
}

public class Implemented implements TestInterface {
    public static String NON_CONST_C = "" ;
}

public class AutoFinal  {

    public static String NON_CONST_A = "" ;

    public static void main(String args[]) {
        TestInterface.NON_CONST_B = "hello-b" ;
        Implemented.NON_CONST_C = "hello-c";
        AutoFinal.NON_CONST_A = "hello-a" ;
        Implemented obj = new Implemented();
    }
}

However, the compiler complains that TestInterface.NON_CONST_B is final --

AutoFinal.java:6: error: cannot assign a value to final variable NON_CONST_B
        TestInterface.NON_CONST_B = "hello-b" ;
                 ^
1 error

why ?

Upvotes: 4

Views: 1425

Answers (4)

Ba Tới Xì Cơ
Ba Tới Xì Cơ

Reputation: 492

In Java, all variables declared in an interface are public static final by default.

Upvotes: 3

Not a bug
Not a bug

Reputation: 4314

As all answers saying that by default all the variables declared in Interface are static final variables.

FYI, you can not declare a static method in interface. You can find the reason in this SO question. however, you can declare Inner Class in an interface that can contain static methods and non static and non final variables.

Upvotes: 0

Kanagaraj M
Kanagaraj M

Reputation: 966

Variables declared in interface are always public static final by default in java. 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.

Upvotes: 2

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

Regarding:

public interface TestInterface {
   public static String NON_CONST_B = "" ; 
}

public class AutoFinal  {    
   public static void main(String args[]) {
      TestInterface.NON_CONST_B = "hello-b" ;
      // ....
   }
}

However, the compiler complains that TestInterface.NON_CONST_B is final --


But it in fact is final whether you explicitly declare it to be or not since it is declared in an interface. You can't have non-final variables (non-constants) in an interface. It's also public and static whether or not it has been explicitly declared as such.

Per the JLS 9.3 Interface Field (Constant) Declarations:

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.

Upvotes: 12

Related Questions