access outer class from inner nested enum

Cel picture Cel · Dec 10, 2011 · Viewed 7.3k times · Source

Is There a Way to Access the Outside?

public class OuterClass  {
    String data;

    public void outerMethod(String data) {
         this.data = data;
    }

    public enum InnerEnum {
        OPTION1("someData"),
        OPTION2("otherData");

        InnerEnum(String data) {
              // Does not work:             
              OuterClass.this.outerMethod(data);
        }
    }
}

Answer

user949300 picture user949300 · Dec 10, 2011

As Eric said, enums are implicitly static. To do what you want, add a method, callOuterMethod(OuterClass oc) that calls oc.outerMethod(data) to do what you want:

public enum InnerEnum {
    OPTION1("someData"),
    OPTION2("otherData");

    final String data;

    InnerEnum(String data) {
       this.data = data;             
    }

    void callOuterMethod(OuterClass oc) {
        oc.outerMethod(data);
    }
}