代码之家  ›  专栏  ›  技术社区  ›  ramgorur

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

  •  4
  • ramgorur  · 技术社区  · 12 年前

    请参阅以下代码--

    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
    

    为什么?

    4 回复  |  直到 12 年前
        1
  •  12
  •   Hovercraft Full Of Eels    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" ;
          // ....
       }
    }
    

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


    但事实上 final,无论您是否显式声明它,因为它是在接口中声明的。接口中不能有非最终变量(非常量)。它也是公共的和静态的,无论它是否被明确声明为公共的和静止的。

    根据 JLS 9.3 Interface Field (Constant) Declarations :

    接口主体中的每个字段声明都是 含蓄地 公共、静态和最终。允许为这些字段冗余地指定任何或所有这些修饰符。

        2
  •  3
  •   Ba Tới Xì CÆ¡    12 年前

    在java中,所有变量都是在Interfacel中声明的 公开静态决赛 违约

        3
  •  2
  •   Kanagaraj M    12 年前

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

        4
  •  0
  •   Community Mohan Dere    9 年前

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

    仅供参考,您不能申报 static 方法。你可以在中找到原因 this SO question. 但是,您可以申报 Inner Class 在一个可以包含 静止的 方法以及非静态和非最终变量。

    推荐文章