在以下代码中,Colours
枚举 GREEN
值的成员字段在枚举定义之外无法访问:
public class Test {
enum Colours {
RED,
GREEN {
public static final int hex = 0x00ff00;
public final int hex2 = 0x00ff00; // Try it without static, just in case...
void f() {
System.out.println(hex); // OK
System.out.println(hex2); // OK
}
},
BLUE
}
public static void main(String[] args) {
System.out.println(Colours.GREEN.hex); // COMPILE ERROR
System.out.println(Colours.GREEN.hex2); // COMPILE ERROR
}
}
有问题的行会导致以下编译器错误:
Error:(38, 41) java: cannot find symbol
symbol: variable hex
location: variable GREEN of type Test.Colours
知道为什么这不起作用吗?我认为 Java 标准禁止这样做,但为什么呢?
最佳答案
根据 JLS §8.9.1. Enum Constants enum
常量主体受适用于匿名类的规则控制,这些规则限制了字段和方法的可访问性:
The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type. The class body is governed by the usual rules of anonymous classes; in particular it cannot contain any constructors. Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type (§8.4.8).
关于Java 枚举值字段在定义之外不可访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55393152/