Barry Fruitman
Barry Fruitman

Reputation: 12666

Can enum instances declare their own public methods?

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...

Upvotes: 5

Views: 148

Answers (1)

ajb
ajb

Reputation: 31699

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.

Upvotes: 4

Related Questions