Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 531
ramgorur Avatar asked Dec 03 '22 21:12

ramgorur


2 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 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.

like image 52
Hovercraft Full Of Eels Avatar answered May 04 '23 01:05

Hovercraft Full Of Eels


In java, all variables was declared in Interfacel are public static final default

like image 32
Ba Tới Xì Cơ Avatar answered May 04 '23 00:05

Ba Tới Xì Cơ