如何在Java中扩展Enum?

时间:2012-12-13 09:02:38

标签: java enums

我有一个来自示例项目的课。但是当我使用这个课时,它会显示一些错误。下面给出了课程。

public  class q extends Enum
{

    private int i = -1;
    private String s = null;

    private q(String s, int i)
    {
       // super(s, i);
        this.s = s;
        this.i  = i;
    }

    public static q valueOf(String s)
    {
        return (q)Enum.valueOf(q.class, s);
    }

    public static q[] values()
    {
        return (q[])a.clone();
    }

    public static final q ANDROID_VERSION;
    public static final q APP_VERSION_CODE;
    public static final q APP_VERSION_NAME;
    public static final q AVAILABLE_MEM_SIZE;
    private static final q a[];

    static 
    {
        APP_VERSION_CODE = new q("APP_VERSION_CODE", 1);
        APP_VERSION_NAME = new q("APP_VERSION_NAME", 2);
        ANDROID_VERSION = new q("ANDROID_VERSION", 6);
        AVAILABLE_MEM_SIZE = new q("AVAILABLE_MEM_SIZE", 11);
        q aq[] = new q[34];
        aq[0] = APP_VERSION_CODE;
        aq[1] = ANDROID_VERSION;
        aq[2] = APP_VERSION_NAME;
        aq[3] = AVAILABLE_MEM_SIZE;
        a = aq;
    }

}

当扩展Enum时,它显示“类型q可能无法明确枚举枚举”错误。如何使用这些字段创建枚举?

如何修改此类以使用枚举(即,我想使用默认的枚举方法,如ordinal(),valueOf(...)等..)?

3 个答案:

答案 0 :(得分:5)

您无法从Enum延伸。您必须声明Enum类,如:

public enum Q {
    TYPE1, TYPE2, TYPE3;
}

您也无法直接实例化枚举类。每种类型的枚举类都由虚拟机实例化一次。

public class MyClass {

    public enum MyEnum{
        TYPE1("Name", 9,1,100000), TYPE2("Name2", 10, 1, 200000);

        private final int androidVersion;
        private final int appVersionCode;
        private final int availableMemSize;
        private final String appVersionName;

        private MyEnum(String appVersionName, int androidVersion, int appVersionCode, int availableMemSize) {
            this.androidVersion = androidVersion;
            this.appVersionCode = appVersionCode;
            this.availableMemSize = availableMemSize;
            this.appVersionName = appVersionName;
        }
    }
    MyEnum mType = MyEnum.TYPE1;
}

答案 1 :(得分:5)

Enums基本上归结为这样的事情:

public Enum Q
{
    TYPE1, TYPE2, TYPE3:
}

// is roughy translated to 

public final class Q
{
    private Q() {}

    public static final Q TYPE1 = new Q();
    public static final Q TYPE2 = new Q();
    public static final Q TYPE3 = new Q();
}

您可以做的更多,但这可以解释为什么您无法实例化Q

答案 2 :(得分:3)

- enum关键字视为合成糖为您设置具有普通继承树的类,但不允许您扩展 java.lang.Enum

<强>例如

public enum TEST {  
    ONE, TWO, THREE;
}