ram*_*rur 4 java static interface
请看下面的代码 -
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然而,编译器抱怨这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
Run Code Online (Sandbox Code Playgroud)
为什么?
Hov*_*els 12
关于:
public interface TestInterface {
public static String NON_CONST_B = "" ;
}
public class AutoFinal {
public static void main(String args[]) {
TestInterface.NON_CONST_B = "hello-b" ;
// ....
}
}
Run Code Online (Sandbox Code Playgroud)
但是,编译器抱怨TestInterface.NON_CONST_B是最终的 -
但它实际上是最终的,无论你是否明确声明它是否是因为它是在接口中声明的.您不能在接口中包含非最终变量(非常量).无论是否已经明确声明它,它也是公共的和静态的.
接口主体中的每个字段声明都是隐式的 public,static和final.允许为这些字段冗余地指定任何或所有这些修饰符.