[英]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是最终的 -
但它实际上是最终的,无论你是否明确声明它是否是因为它是在接口中声明的。 您不能在接口中包含非最终变量(非常量)。 无论是否已经明确声明它,它也是公共的和静态的。
接口主体中的每个字段声明都是隐式的 public,static和final。 允许为这些字段冗余地指定任何或所有这些修饰符。
在java中,所有在Interfacel中声明的变量都是public static final default
在java中,默认情况下,接口中声明的变量始终是public static final。 接口变量是静态的,因为Java接口本身无法实例化; 必须在没有实例的静态上下文中分配变量的值。 最终修饰符确保分配给接口变量的值是一个真正的常量,不能由程序代码重新赋值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.