Internal enumeration in a non-stationary context

As I understand it, internal enums are always explicitly implicitly static in java. This means that I cannot access the 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; } 

It was pretty convenient for me to simply override the method in each enum constant, so I could use it in my outer class. Is this a bad programming style in java because it is actually forbidden?

Is there a way to create an internal enumeration with access to my instance variables?

Thanks in advance.

+6
source share
2 answers

Is there a way to create an internal enumeration with access to my instance variables?

An enum is a compile-time construction (predefined), so any external data inside one should be easily accessible to the compiler before execution.

Unless you explicitly pass a variable (or some link containing it, in this case this ), to a method inside enum , you cannot reference it.

+2
source

It was pretty convenient for me to simply override the method in each enum constant, so I could use it in my outer class. Is this a bad programming style in java because it is actually forbidden?

There is nothing inherently wrong with redefining methods in your enumeration constants. As with any other language construct, misuse is not so bad.

I'm not sure what you mean by “so I could use it in my outer class,” but in general the enumerations should not be very dependent on the outer code. They are intended to describe a fixed set of constant values, and to achieve this requires little or no connection with other types (unlike basic types such as primitives and strings). This puts me as a dubious design for an enum constant for accessing instance level elements of an external type.

+1
source

Source: https://habr.com/ru/post/957871/


All Articles