(JAVA Enums)-枚举常量中的匿名类 [英] (JAVA Enums) - Anonymous class inside enum constant

查看:324
本文介绍了(JAVA Enums)-枚举常量中的匿名类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天!



我有一个仅实现一种方法的接口。我不想制作几个都实现一个方法的类,因此我决定改用匿名类。



我对某些静态项目使用枚举,这些枚举有实例我的界面。但是,当我尝试在枚举常量中创建一个匿名类时,我的IDE(eclipse)实际上并没有告诉我任何事情(好像它在代码块之外)。



问题如下:我可以在枚举常量中使用匿名类吗?



如果我的文字不清楚(对不起,我不是英语),请参阅



代码示例

  / ** 
*我的接口
* /

公共接口IPotato {

public void eatPotato();
}

/ **
*我的枚举类
* /
公共枚举PotatoEnum {

I_WANT_TO_EAT_POTATO(new IPotato (){
@Override
public void eatPotato(){
//无法在此处放置代码。
}));

私人IPotato _myAnonymousClass;
private PotatoEnum(IPotatoonymousClass){
this._myAnonymousClass = onymousClass;
}

公共IPotato getPotato(){
return _myAnonymousClass;
}

}


解决方案

您可以这样做,这是一个非常有效的解决方案。



作为建议,让您的枚举实现您的接口以使代码更具可读性:

 公共枚举PotatoEnum实现IPotato {

I_WANT_TO_EAT_POTATO(){

@Override
public void eatPotato(){
//无法在此处放置代码。

}},//更多ENUMS;

}


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

    }

解决方案

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 ;

    }

这篇关于(JAVA Enums)-枚举常量中的匿名类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆