Can enums be subclassed to add new elements?

前端 未结 15 1988
臣服心动
臣服心动 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:32

    I suggest you take the other way around approach.

    Instead of extending the existing enumeration, create a larger one and create a subset of it. For exemple if you had an enumeration called PET and you wanted to extend it to ANIMAL you should do this instead:

    public enum ANIMAL {
        WOLF,CAT, DOG
    } 
    EnumSet pets = EnumSet.of(ANIMAL.CAT, ANIMAL.DOG);
    

    Be careful, pets is not an immutable collections, you might want to use Guava or Java9 for more safety.

提交回复
热议问题