如何在Java中扩展Enum?

Dev*_*man 5 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;
    }

}
Run Code Online (Sandbox Code Playgroud)

当扩展Enum时,它显示" 类型q可能没有明确地枚举Enum "错误.如何使用这些字段创建枚举?

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

tha*_*sma 6

你无法延伸Enum.你必须声明一个Enum类,如:

public enum Q {
    TYPE1, TYPE2, TYPE3;
}
Run Code Online (Sandbox Code Playgroud)

而且你也无法直接实例化枚举类.每种类型的枚举类都由虚拟机实例化一次.

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;
}
Run Code Online (Sandbox Code Playgroud)


ata*_*man 5

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

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();
}
Run Code Online (Sandbox Code Playgroud)

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