java - 除非用常量表达式初始化,否则不能在非静态内部类型中将字段声明为静态

标签 java

public class Test {

public enum Directions {
        NORTH, WEST, SOUTH, EAST
    }

    static final Directions D1 = Directions.NORTH;

    static class Inner {
        static final Directions D2 = Directions.NORTH;
    }

    class Inner2 {
        static final Directions D3 = Directions.NORTH;
    }

}

我收到标题中的 IDE 错误,指的是变量 D3。有人可以向我解释一下吗?为什么我不能在非静态的内部类中声明静态变量,为什么枚举值不是常量?

最佳答案

JLS §8.1.3 Inner Classes and Enclosing Instances

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.


Why is an Enum entry not considered a constant variable?

A variable of primitive type or type String, that is final and initialized with a compile-time constant expression (§15.28), is called a constant variable.

关于java - 除非用常量表达式初始化,否则不能在非静态内部类型中将字段声明为静态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37509919/

相关文章:

java - 使用Flink窗口和折叠功能,元素丢失?

java - 使用 RegEx 在最后一个点之后查找字符串并删除以大写字母开头的最后一个单词

java - Java 如何像 C 那样写/读硬件端口? (outb、inb 等..)

java - 当使用 Type 而不是 Class<T> 时,有没有办法避免使用泛型进行强制转换

java - 将继承的变量强制转换为子类

java 类与自身的关联

java - 使用 Java 访问 HDFS 中的文件

java - 如何更改最里面的嵌套语句,但保留外部语句?

java - Java 中的扩展方法可能不会破坏二进制向后兼容性吗?

java - 在 x 和 y 方向重复时设置 BitmapDrawable 的偏移量?