I have the following simple enum in which I want to declare and use a few constants (as the constructor arguments):
public enum MyEnum {
A(FOO), B(BAR);
MyEnum(String foo) {
}
static final String FOO = "foo";
static final String BAR = "bar";
}
However, the compiler gives me the following error:
Error:(3, 7) java: illegal forward reference
Error:(3, 15) java: illegal forward reference
If I try to refactor the original enum in an IDE like Intellij IDEA, it extracts the constructor arguments into constants of an inner class, and the following code compiles ok:
SNIPPET 1:
public enum MyEnum {
A(Constants.FOO), B(Constants.BAR);
MyEnum(String foo) {
}
private static class Constants {
public static final String FOO = "foo";
public static final String BAR = "bar";
}
}
I also found out that even without an inner constants class, the code compiles ok if the constants are specified using fully classified names:
SNIPPET 2:
public enum MyEnum {
A(MyEnum.FOO), B(MyEnum.BAR);
MyEnum(String foo) {
}
static final String FOO = "foo";
static final String BAR = "bar";
}
Questions:
Could anybody please explain why the code in snippet 2 compiles while the original one does not? Is it some linking issue?
When choosing between solutions of snippet 1 and 2, which approach is better (cleaner)? To me, snippet 1 (inner class with constants) looks cleaner, but I'm concerned with an extra cost of an inner class: there's gonna be 20 enums in the app +20 inner classes in that case.
Thanks!