Search code examples
javaenumsanonymous-class

(JAVA Enums) - Anonymous class inside enum constant


Good day!

I have an interface which only implements one single method. I dont feel like making several class which all implement this one single method therefore I decided to use anonymous classes instead.

I use enums for certain static items, these enums have instances of my interface. However, when I try to make an anonymous class inside my enum constants my IDE (eclipse) literally tells me nothing (as if it is outside a code block).

My question is as follows: Can I use anonymous classes inside my enum constants?

If my text was unclear (Sorry im not english) please see the example below.

Code example

/**
 * My Interface 
 */

public interface IPotato {

    public void eatPotato();
} 

/**
* My enum class
*/
    public enum PotatoEnum {

        I_WANT_TO_EAT_POTATO(new IPotato() {
            @Override
            public void eatPotato() {
                // Cant put code here.
            } });

        private IPotato _myAnonymousClass;
        private PotatoEnum(IPotato anonymousClass){
            this._myAnonymousClass = anonymousClass;
        }

        public IPotato getPotato(){
            return _myAnonymousClass;
        }

    }

Solution

  • You could do that, it is a perfectly valid solution.

    As a recommendation, make your enum implement your interface to make the code more readable:

    public enum PotatoEnum implements IPotato{
    
            I_WANT_TO_EAT_POTATO(){
    
                @Override
                public void eatPotato() {
                    // Cant put code here.
    
                }},//more ENUMS ;
    
        }