【发布时间】:2014-12-15 19:07:15
【问题描述】:
我是 Java 新手。听说Interface只能有静态变量,对吗?
【问题讨论】:
-
public static final变量。
标签: java
我是 Java 新手。听说Interface只能有静态变量,对吗?
【问题讨论】:
public static final 变量。
标签: java
是的,因为接口不能被实例化,所以实例状态没有意义。
快速的 Google 搜索找到了相同的答案。
【讨论】:
这是正确的。原因是Java接口不能自己实例化。您必须实例化实现该接口的类的实例。因此,变量的值必须在静态上下文中赋值,因为在这种情况下将不存在任何实例。
它们还需要声明为final,以确保分配给接口变量的值是真正的常量,在运行时其他程序代码无法更改。
【讨论】:
如评论中所述
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.
【讨论】: