是“公共静态最终版本"吗? Java接口中的常量是否多余? [英] Is "public static final" redundant for a constant in a Java interface?

查看:123
本文介绍了是“公共静态最终版本"吗? 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接口中的常量是否是多余的?对于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.

这篇关于是“公共静态最终版本"吗? Java接口中的常量是否多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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