Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enum instances declare their own public methods?

Tags:

java

enums

Please consider the following code sample:

public enum MyEnum {

    FIRST {
        @Override
        public void someMethod() {
            ...
        }
    },

    SECOND {
        @Override
        public void someMethod() {
            ...
        }

        public void someOtherMethod() {
            ...
        }
    };


    public abstract void someMethod();
}         

Is it possible to call someOtherMethod()? I tried MyEnum.SECOND.someOtherMethod() but the IDE could not resolve it.

Thanks in advance...

like image 937
Barry Fruitman Avatar asked Oct 01 '22 15:10

Barry Fruitman


1 Answers

MyEnum.SECOND.someOtherMethod() is illegal because of this rule pertaining to the class bodies on enum constants:

Instance methods declared in these class bodies may be invoked outside the enclosing enum type only if they override accessible methods in the enclosing enum type. [JLS §8.9.1]

So since someOtherMethod() doesn't override a MyEnum method, you can't invoke it outside of MyEnum. You could, however, invoke it somewhere in the body of SECOND, and you might even be able to invoke it from the body of one of the other enum constants like FIRST, although I haven't tried it and frankly that would be a bit weird.

like image 142
ajb Avatar answered Oct 03 '22 06:10

ajb