Why does the compiler say that the public static field in the interface is “final”, although it is not

See 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 it TestInterface.NON_CONST_Bis final -

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

why?

+4
source share
4 answers

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 in fact, it is final unless you explicitly declare it or not, as he declared in the interface. You cannot have unconfigured variables (not constants) in the interface. It is also public and static regardless of whether it has been explicitly declared as such.

JLS 9.3. ():

, . .

+12

java Interfacel public static final

+3

, , public static final java. , Java ; , . , , , , .

+2

, , , , .

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

0
source

All Articles