It is a compile-time error for the constructors, instance initializer blocks, or instance variable initializer expressions of an enum constant e to refer to e or to an enum constant of the same type that is declared to the right of e.
这里的规范只是意味着您不能以名称引用,因为e所引用的字段尚未初始化.这并不意味着你无法访问这个.
它基本上与任何其他初始化器(如int x = x;)相同.
我们可以看到为什么像(Ideone)这样的例子:
enum Example {
INSTANCE {{
subversion();
}};
static void subversion() {
System.out.println(INSTANCE);
}
public static void main(String[] args) {
System.out.println(INSTANCE);
}
}
哪个输出
null
INSTANCE
I found that if mMap is private, it cannot be referenced in the instance initializer.
您可以将呼叫限定为super.mMap.put(…);.私有的mMap不是继承的,但是它可以从内部类中访问. I also covered this here.简而言之,简单的名称mMap是指一个不存在的Derp的外部实例.
我们可以用(Ideone)这样的例子来证实这一点:
class Example {
private int x;
class Inner extends Example {{
x = 1; // refers to the outer instance
super.x = 2; // refers to the inner instance
}}
public static void main(String[] args) {
Example outer = new Example();
Example inner = outer.new Inner();
System.out.println(outer.x); // prints 1
System.out.println(inner.x); // prints 2
}
}
除了你的情况,FOO是静态的,所以没有外部实例,因此编译错误.