繁体   English   中英

为什么编译器说接口中的公共静态字段是“最终的”,尽管它不是

[英]why compiler says a public static field in interface is “final” although it is not

请看下面的代码 -

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();
    }
}

但是,编译器抱怨TestInterface.NON_CONST_B是最终的 -

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

为什么?

关于:

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

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

但是,编译器抱怨TestInterface.NON_CONST_B是最终的 -


但它实际上最终的,无论你是否明确声明它是否是因为它是在接口中声明的。 您不能在接口中包含非最终变量(非常量)。 无论是否已经明确声明它,它也是公共的和静态的。

根据JLS 9.3接口字段(常量)声明

接口主体中的每个字段声明都是隐式的 public,static和final。 允许为这些字段冗余地指定任何或所有这些修饰符。

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

在java中,默认情况下,接口中声明的变量始终是public static final。 接口变量是静态的,因为Java接口本身无法实例化; 必须在没有实例的静态上下文中分配变量的值。 最终修饰符确保分配给接口变量的值是一个真正的常量,不能由程序代码重新赋值。

正如所有答案都说默认情况下在Interface中声明的所有变量都是静态最终变量。

仅供参考,您无法在界面中声明static方法。 你可以在这个SO问题中找到原因 但是,您可以在可以包含static方法和非静态和非最终变量的接口中声明Inner Class

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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