public enum MyEnum1 {
FOO(BAR), BAR(FOO);
private MyEnum1 other;
private MyEnum1(MyEnum1 other) {
this.other = other;
}
public MyEnum1 getOther() {
return other;
}
}
MyEnum1
生成错误 Cannot reference a field before it is defined
,这是可以理解的,因为声明顺序在这里很重要。但是为什么下面的编译?
public enum MyEnum2 {
FOO { public MyEnum2 getOther() { return BAR; } },
BAR { public MyEnum2 getOther() { return FOO; } };
public abstract MyEnum2 getOther();
}
FOO
在定义 BAR
之前引用 BAR
,我错了吗?
最佳答案
A class or interface type T will be initialized immediately before the first occurrence of any one of the following:
T is a class and an instance of T is created.
T is a class and a static method declared by T is invoked.
A static field declared by T is assigned.
A static field declared by T is used and the field is not a constant variable (§4.12.4).
T is a top level class (§7.6), and an assert statement (§14.10) lexically nested within T (§8.1.3) is executed.
和
The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type.
所以
FOO { public MyEnum2 getOther() { return BAR; } },
BAR { public MyEnum2 getOther() { return FOO; } };
您正在创建两个扩展 MyEnum2
的匿名类。
当 BAR
在您调用 Foo.getOther()
时最终被引用,或者某些其他代码段执行 MyEnum2.Bar
时,类型将被初始化。
关于java - 看来我可以*在定义之前引用一个字段*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18382046/