Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to extend Java Enums?

Tags:

Here's what I am looking to accomplish, I have a class that has an enum of some values and I want to subclass that and add more values to the enum. This is a bad example, but:

public class Digits {  public enum Digit  {   0, 1, 2, 3, 4, 5, 6, 7, 8, 9  } }  public class HexDigits extends Digits {  public enum Digit  {   A, B, C, D, E, F  } } 

so that HexDigits.Digit contains all Hex Digits. Is that possible?

like image 917
CaseyB Avatar asked Apr 15 '10 01:04

CaseyB


People also ask

Can an enum extend another?

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

Why we Cannot extend enum?

In byte code, any enum is represented as a class that extends the abstract class java. lang. Enum and has several static members. Therefore, enum cannot extend any other class or enum : there is no multiple inheritance.

Can enum extend interface?

Enum, it can not extend any other class or enum and also any class can not extend enum. So it's clear that enum can not extend or can not be extended. But when there is a need to achieve multiple inheritance enum can implement any interface and in java, it is possible that an enum can implement an interface.


2 Answers

No it's not possible. The best you can do is make two enums implement and interface and then use that interface instead of the enum. So:

interface Digit {   int getValue(); }  enum Decimal implements Digit {   ZERO, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE;    private final int value;    Decimal() {     value = ordinal();   }    @Override   public int getValue() {     return value;   } }  enum Hex implements Digit {   A, B, C, D, E, F;    private final int value;    Hex() {     value = 10 + ordinal();   }    @Override   public int getValue() {     return value;   } } 
like image 74
cletus Avatar answered Oct 11 '22 14:10

cletus


No.

Enums cannot be subclassed.

The reasoning here is that an enumeration defines a fixed number of values. Subclassing would break this.

like image 44
Thilo Avatar answered Oct 11 '22 13:10

Thilo