Can enums be subclassed to add new elements?

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

    In case you missed it, there's a chapter in the excellent Joshua Bloch's book "Effective Java, 2nd edition".

    • Chapter 6 - Enums and Annotations
    • Item 34 : Emulate extensible enums with interfaces

    Just the conclusion :

    A minor disadvantage of the use of interfaces to emulate extensible enums is those implementations cannot be inherited from one enum type to another. In the case of our Operation example, the logic to store and retrieve the symbol associated with an operation is duplicated in BasicOperation and ExtendedOperation. In this case, it doesn’t matter because very little code is duplicated. If there were a a larger amount of shared functionality, you could encapsulate it in a helper class or a static helper method to eliminate the code duplication.

    In summary, while you cannot write an extensible enum type, you can emulate it by writing an interface to go with a basic enum type that implements the interface. This allows clients to write their own enums that implement the interface. These enums can then be used wherever the basic enum type can be used, assuming APIs are written in terms of the interface.

提交回复
热议问题