Can enums be subclassed to add new elements?

前端 未结 15 1853
臣服心动
臣服心动 2020-11-22 12:02

I want to take an existing enum and add more elements to it as follows:

enum A {a,b,c}

enum B extends A {d}

/*B is {a,b,c,d}*/

Is this po

15条回答
  •  太阳男子
    2020-11-22 12:38

    I tend to avoid enums, because they are not extensible. To stay with the example of the OP, if A is in a library and B in your own code, you can't extend A if it is an enum. This is how I sometimes replace enums:

    // access like enum: A.a
    public class A {
        public static final A a = new A();
        public static final A b = new A();
        public static final A c = new A();
    /*
     * In case you need to identify your constant
     * in different JVMs, you need an id. This is the case if
     * your object is transfered between
     * different JVM instances (eg. save/load, or network).
     * Also, switch statements don't work with
     * Objects, but work with int.
     */
        public static int maxId=0;
        public int id = maxId++;
        public int getId() { return id; }
    }
    
    public class B extends A {
    /*
     * good: you can do like
     * A x = getYourEnumFromSomeWhere();
     * if(x instanceof B) ...;
     * to identify which enum x
     * is of.
     */
        public static final A d = new A();
    }
    
    public class C extends A {
    /* Good: e.getId() != d.getId()
     * Bad: in different JVMs, C and B
     * might be initialized in different order,
     * resulting in different IDs.
     * Workaround: use a fixed int, or hash code.
     */
        public static final A e = new A();
        public int getId() { return -32489132; };
    }
    

    There are some pits to avoid, see the comments in the code. Depending on your needs, this is a solid, extensible alternative to enums.

提交回复
热议问题