Can enums be subclassed to add new elements?

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

    Having had this same problem myself I'd like to post my perspective. I think that there are a couple motivating factors for doing something like this:

    • You want to have some related enum codes, but in different classes. In my case I had a base class with several codes defined in an associated enum. At some later date (today!) I wanted to provide some new functionality to the base class, which also meant new codes for the enum.
    • The derived class would support both the base classes' enum as well as its own. No duplicate enum values! So: how to have an enum for the subclass that includes the enum's of its parent along with its new values.

    Using an interface doesn't really cut it: you can accidentally get duplicate enum values. Not desirable.

    I ended up just combining the enums: this ensures that there cannot be any duplicate values, at the expense of being less tightly tied to its associated class. But, I figured the duplicate issue was my main concern...

提交回复
热议问题