简体   繁体   中英

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 ?

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.

在java中,所有在Interfacel中声明的变量都是public static final default

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM