I’m trying to create a private static final variable inside of an enum, but I keep getting a compile error. Does anyone know how to fix this?
Multiple markers at this line
- Syntax error, insert “Identifier” to complete EnumConstantHeaderName
- Syntax error, insert “}” to complete EnumBody
class Foo {
...
public enum MyEnum {
private static final String MY_STRING = "a string I use in a constructor";
private static final String MY_OTHER_STRING = "a string I use in another constructor";
MyEnumType(1, MY_STRING),
MyEnumType2(2, MY_STRING),
MyEnumType3(3, MY_OTHER_STRING);
MyEnum(int num, String str) {
...
}
}
...
}
The enum constants need to be the first elements in the Enumeration. A version of your code that compiles:
* EDIT *
Based off edits made to your original question, I see what you are trying to do. No its not possible to use constants in your enum literal declarations that are declared in the enum definition itself. This is because the literal declarations MUST be the first elements in the enum. This is mandated by the Java Language Specification. Two quick things though:
private static final Strings. This gives youabsolutely no benefit whatsoever over using string literals instead,
which would solve the problem.
public static final) then you would need to do so outside of the enum.Strings
Alternatively you can declare your Enums as nested elements of a class which defines the
private static final String‘s for you.Some pseudocode: