(JAVA Enums) - Anonymous class inside enum constant

半腔热情 提交于 2019-12-08 08:47:01

问题


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;
        }

    }

回答1:


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 ;

    }



回答2:


Simply yes

By doing this you are doing something like that:

I_WANT_TO_EAT_POTATO(An object of a virtual class that implments IPotato class);

same as :

I_WANT_TO_EAT_POTATO(Passing any parameter defined by constructor);

See Enum constants as an Inner Classes and you are passing them parameters of their construcors




回答3:


You can to that. The reason of your mistake is that you have two public identifier (enum and interface) in single file . remove public from enum and it will work

public interface IPotato {
    public void eatPotato();
}

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;
    }

}


来源:https://stackoverflow.com/questions/35156587/java-enums-anonymous-class-inside-enum-constant

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!