Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner Enum in non-static context

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.

like image 968
ferrerverck Avatar asked Nov 11 '13 23:11

ferrerverck


2 Answers

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.

like image 169
yamafontes Avatar answered Sep 28 '22 05:09

yamafontes


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.

like image 36
Mike Strobel Avatar answered Sep 28 '22 05:09

Mike Strobel