有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

对于Java接口中的常量,“publicstaticfinal”是多余的吗?

此代码:

interface Config {
    int MAX_CONN = 20;
}

按照我的预期编译和工作。看起来这与:

interface Config {
    public static final int MAX_CONN = 20;
}

对于Java接口中的常量,“publicstaticfinal”是多余的吗?Java 1.1、1.2、1.3、1.4等是否也是如此,。。。,还是在Java版本中有所改变


共 (6) 个答案

  1. # 1 楼答案

    接口变量是静态的,因为Java接口本身无法实例化。变量的值必须在静态上下文中赋值-不存在实例。最后一个修饰符确保分配给接口变量的值是不能由程序代码重新分配的真常量

  2. # 2 楼答案

    接口变量始终是静态的和最终的

  3. # 3 楼答案

    接口中声明的变量是隐式的public static final。这就是JLS 9.3所说的:

    Every field declaration in the body of an interface is implicitly public, static, and final. It is permitted to redundantly specify any or all of these modifiers for such fields.

    阅读JLS,了解为什么会这样做

    看看这个SO answer

    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. The final modifier ensures the value assigned to the interface variable is a true constant that cannot be re-assigned by program code.

  4. # 4 楼答案

    接口variables是隐式的staticfinal,因为Java接口不能单独实例化

    Interfaces are declared using the interface keyword, and may only contain method signature and constant declarations (variable declarations that are declared to be both static and final). An interface may never contain method definitions.

    http://en.wikipedia.org/wiki/Interface_(Java)

  5. # 5 楼答案

    如果必须将interface重构为类,那么保留冗余的public static final可能更为实际。(这听起来很奇怪,因为每个IDE都将这些标记为冗余信息)

    公平地说,编辑是不可能做到这一点的:如果不更改许多其他位置(因为接口使用implements,而从类继承使用extends

    编辑#2事实上,常量接口可以被视为反模式,请参见wikipedia - Constant Interface

  6. # 6 楼答案

    接口:系统需求服务

    在接口中,变量默认由公共、静态、最终访问修饰符赋值。因为:

    public:有时接口可能会放在其他包中。所以它需要从项目中的任何地方访问变量

    静态:因此,不完整的类无法创建对象。所以在项目中,我们需要访问不带对象的变量,这样我们就可以在

    interface_filename.variable_name
    

    final:假设一个接口由多个类实现,所有类都尝试访问和更新接口变量。因此,它会导致数据变化的不一致性,并影响其他所有类。所以它需要用final声明访问修饰符