[英]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.