javaenumssyntax

Enums: methods exclusive to each one of the instances


From another question I have learnt that it is possible in Java to define specific methods for each one of the instances of an Enum:

public class AClass {

    private enum MyEnum{
        A { public String method1(){ return null; } },
        B { public Object method2(String s){ return null; } },
        C { public void method3(){ return null; } } ;
    }

    ...
}

I was surprised that this is even possible, do this "exclusive methods" specific to each instance have a name to look for documentation?

Also, how is it supposed to be used? Because the next is not compiling:

    private void myMethod () {
        MyEnum.A.method1();
    }

How am I supposed to use these "exclusive" methods?


Solution

  • You cannot refer to those methods, because you are effectively creating anonymous (*) class for each enum. As it is anonymous, you can reference such methods only from inside your anonymous class itself or through reflection.

    This technique is mostly useful when you declare abstract method in your enumeration, and implement that method for each enum individually.

    (*) JLS 8.9 Enums part says: "The optional class body of an enum constant implicitly defines an anonymous class declaration (§15.9.5) that extends the immediately enclosing enum type."