As I understood inner enums are always explicitly оr implicitly static in java. Which means I can't access instance fields from my inner enum class.
public class InnerEnum {
private enum SomeInnerEnum {
VALUE1() {
@Override
public void doSomething() {
// ERROR: WON'T COMPILE
// Cannot make static reference
// to non-static field i
System.out.println(i);
}
},
VALUE2() {
@Override
public void doSomething() {
// do something else with i
}
};
public abstract void doSomething();
}
private int i = 10;
}
I have found it pretty convenient to just override method in each enum constant, so I could use it in my outer class. Is it a bad programming style in java, because it is actually forbidden?
Is there any way to create inner enum with an access to my instance variables?
Thanks in advance.
Is there any way to create inner enum with an access to my instance variables?
An enum
is a compile time construct (predefined), and therefore any external data inside of one must be readily available to the compiler before runtime.
Unless you explicitly pass the variable (or some reference containing it, in your case this
) down to the method inside the enum
, you won't be able to reference it.
I have found it pretty convenient to just override method in each enum constant, so I could use it in my outer class. Is it a bad programming style in java, because it is actually forbidden?
There is nothing inherently wrong with overriding methods in your enum constants. As with any other language construct, it is not bad practice when used appropriately.
I'm not sure what you mean by "so I could use it in my outer class," but in general, enums should not be heavily dependent on external code. They are meant to describe a fixed set of constant values, and little or no coupling with other types should be required to accomplish that (beyond core types like primitives and strings, anyway). It strikes me as questionable design for an enum constant to access instance-level members of an outer type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With