Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can enums be subclassed to add new elements?

Tags:

java

enums

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 possible in Java?

like image 803
Mike Avatar asked Sep 12 '09 09:09

Mike


People also ask

Can enums be subclassed?

We've learned that we can't create a subclass of an existing enum. However, an interface is extensible. Therefore, we can emulate extensible enums by implementing an interface.

Is it possible to extend enum 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 we override enum?

You cannot extend, override or inherit an enum .

Can enums be changed?

4) Enum constants are implicitly static and final and can not be changed once created.


2 Answers

No, you can't do this in Java. Aside from anything else, d would then presumably be an instance of A (given the normal idea of "extends"), but users who only knew about A wouldn't know about it - which defeats the point of an enum being a well-known set of values.

If you could tell us more about how you want to use this, we could potentially suggest alternative solutions.

like image 157
Jon Skeet Avatar answered Sep 24 '22 10:09

Jon Skeet


Enums represent a complete enumeration of possible values. So the (unhelpful) answer is no.

As an example of a real problem take weekdays, weekend days and, the union, days of week. We could define all days within days-of-week but then we would not be able to represent properties special to either weekdays and weekend-days.

What we could do, is have three enum types with a mapping between weekdays/weekend-days and days-of-week.

public enum Weekday {     MON, TUE, WED, THU, FRI;     public DayOfWeek toDayOfWeek() { ... } } public enum WeekendDay {     SAT, SUN;     public DayOfWeek toDayOfWeek() { ... } } public enum DayOfWeek {     MON, TUE, WED, THU, FRI, SAT, SUN; } 

Alternatively, we could have an open-ended interface for day-of-week:

interface Day {     ... } public enum Weekday implements Day {     MON, TUE, WED, THU, FRI; } public enum WeekendDay implements Day {     SAT, SUN; } 

Or we could combine the two approaches:

interface Day {     ... } public enum Weekday implements Day {     MON, TUE, WED, THU, FRI;     public DayOfWeek toDayOfWeek() { ... } } public enum WeekendDay implements Day {     SAT, SUN;     public DayOfWeek toDayOfWeek() { ... } } public enum DayOfWeek {     MON, TUE, WED, THU, FRI, SAT, SUN;     public Day toDay() { ... } } 
like image 43
Tom Hawtin - tackline Avatar answered Sep 25 '22 10:09

Tom Hawtin - tackline