46

Possible Duplicate:
add values to enum

Why enums in Java cannot inherit from other enums? Why is this implemented this way?

Community
  • 1
  • 1
Szymon Lipiński
  • 27,098
  • 17
  • 75
  • 77
  • http://stackoverflow.com/questions/55375/add-values-to-enum – Bill K Dec 10 '09 at 22:12
  • 3
    I would rephrase you question. Why enums cannot have an abstract base? The accepted answer to the question cited by Bill explains why you cannot extend enums with other values, but it's still not clear to me why they cannot share a base implementation. – Alexander Pogrebnyak Dec 10 '09 at 22:19

1 Answers1

85

Example stolen from here

Because adding elements to an enum would effectively create a super class, not a sub class.

Consider:

 enum First {One, Two}   
 enum Second extends First {Three, Four}   

 First a = Second.Four;   // clearly illegal 
 Second a = First.One;  // should work

This is the reverse of the way it works with regular classes. I guess it could be implemented that way but it would be more complicated to implement than it would seems, and it would certainly confuse people.

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
  • 3
    Probably what you want is First implements MyInterface Second implements MyInterface Then use MyInterface for union of the two groups – user1176505 Feb 12 '13 at 11:09
  • 2
    Would First a = Second.One be an illegal statement? – Timothy Swan Sep 05 '14 at 16:18
  • @TimothySwan The referenced code won't be compiled, since an exception will be thrown at the `enum Second extends First {Three, Four}` line. – Pavel Jul 29 '16 at 03:13