(JAVA Enums) - Anonymous class inside enum constant

眉间皱痕 提交于 2019-12-06 15:41:02
user902383

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 ;

    }

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

David Mumladze

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

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