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/