Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java enum inheritance [duplicate]

Tags:

java

Possible Duplicate:
add values to enum

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

like image 540
Szymon Lipiński Avatar asked Dec 10 '09 22:12

Szymon Lipiński


People also ask

Can enums have inheritance Java?

Java Enum and Interface As we have learned, we cannot inherit enum classes in Java. However, enum classes can implement interfaces.

Can enums have inheritance?

Nope. it is not possible. Enum can not inherit in derived class because by default Enum is sealed.

Can one enum extend another in Java?

No, we cannot extend an enum in Java. Java enums can extend java. lang. Enum class implicitly, so enum types cannot extend another class.

Can an enum extend another?

Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.


1 Answers

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.

like image 59
TofuBeer Avatar answered Oct 09 '22 03:10

TofuBeer