Regarding the first question: you cannot have separate constructors, but you can work around this as follows:
public enum EnumTest { ONE() { void init() { val = 2; } }, TWO() { void init() { val = 1; } }; protected int val; abstract void init(); EnumTest() { init(); } }
Thus, you have technically separate initialization methods for different constants.
Another way is to use initializer sections:
public enum EnumTest { ONE() {{ val = 2; }}, TWO() {{ val = 1; }}; protected int val; }
As for your second question: constant fields are not available at the time of enumeration creation, because constant variables are available for static fields. For example, this code compiles correctly:
public enum EnumTest { ONE, TWO; public static final String ONE_STRING = ONE.toString(); }
If access to ONE_STRING from the constructor was allowed, you would either have an infinite initialization cycle, or would have access to an uninitialized enumeration constant.
Tagir valeev
source share