【问题标题】:Interface can have only static variables in JAVA? [duplicate]接口在JAVA中只能有静态变量吗? [复制]
【发布时间】:2014-12-15 19:07:15
【问题描述】:

我是 Java 新手。听说Interface只能有静态变量,对吗?

【问题讨论】:

  • public static final 变量。

标签: java


【解决方案1】:

是的,因为接口不能被实例化,所以实例状态没有意义。

快速的 Google 搜索找到了相同的答案。

http://www.coderanch.com/t/245071/java-programmer-SCJP/certification/final-member-variables-interfaces

【讨论】:

    【解决方案2】:

    这是正确的。原因是Java接口不能自己实例化。您必须实例化实现该接口的类的实例。因此,变量的值必须在静态上下文中赋值,因为在这种情况下将不存在任何实例。

    它们还需要声明为final,以确保分配给接口变量的值是真正的常量,在运行时其他程序代码无法更改。

    【讨论】:

      【解决方案3】:

      如评论中所述

      public static final variables
      
      1. Interface variables are static because Java interfaces cannot be instantiated in their own right; the value of the variable must be assigned in a static context in which no instance exists. 
      
      2. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-10-30
        • 2013-06-14
        • 1970-01-01
        • 2019-11-24
        • 2014-11-01
        • 2015-01-04
        • 1970-01-01
        • 2018-08-14
        相关资源
        最近更新 更多