是“public static final"吗?Java 接口中的常量是多余的吗? [英] Is "public static final" redundant for a constant in a Java interface?

查看:24
本文介绍了是“public static final"吗?Java 接口中的常量是多余的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码:

interface Config {
    int MAX_CONN = 20;
}

按照我的预期编译和工作.看起来是这样的:

compiled and worked as I expected. It looks like this is the same as:

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

对于 Java 接口中的常量来说,public static final"是多余的吗?对于 Java 1.1、1.2、1.3、1.4、...、1.8,这是真的还是在 Java 版本中发生了变化?

Is "public static final" redundant for a constant in a Java interface? Is this true for Java 1.1, 1.2, 1.3, 1.4,..., 1.8 or did it change in a Java release?

推荐答案

Interface 中声明的变量是隐式的public static final.这就是 JLS 9.3说:

Variables declared in Interface are implicitly public static final. This is what JLS 9.3 says :

接口主体中的每个字段声明都是隐式的public、static 和 final.允许为此类字段冗余指定任何或所有这些修饰符.

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 以了解这样做的原因.

Read through the JLS to get an idea why this was done.

看看这个SO答案:

接口变量是静态的,因为 Java 接口本身不能被实例化;变量的值必须在不存在实例的静态上下文中分配.final 修饰符确保分配给接口变量的值是一个真正的常量,不能被程序代码重新分配.

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.

这篇关于是“public static final"吗?Java 接口中的常量是多余的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆