Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why not extending from Enum<E extends Enum<E>>

Tags:

java

enums

I stumbled over the following problem that i can't extend and implement from this class which is defined in Java 1.5 (java.lang package)

public abstract class Enum<E extends Enum<E>> {...
}..

The problem i have is to create my own enum type which has different ordinal values. I don't want to implement it by using different name of ordinal like getCode() etc. So i thought i could go the way to extend the above class.

public final class XYZ extends Enum<XYZ> { //Does not work.
  //
  A("A", 1),
  B("B", 7);
  .
}

I know that i can do the following:

public enum NEWEnum {
   A(1),
   B(7);

   private int code;
   private NEWEnum(int code) {
     this.code = code;
   }
   public int getCode() {
     return this.code;
   }
}

I would prefer to have the usual namings in Enum's like ordinal() and name() instead.

like image 304
khmarbaise Avatar asked Dec 27 '22 02:12

khmarbaise


2 Answers

Enum gets special treatment by the compiler and classes like EnumSet make assumptions based on this treatment. The behavior of Enum methods like ordinal() and name() is strictly defined and implementing them yourself to replicate this behavior makes no sense. Also the syntax to declare enum values is only valid in an enum and wont compile in a class.

It is important to remember that you should never use ordinal() yourself, so defining it to suit your problem makes no sense.

like image 35
josefx Avatar answered Jan 05 '23 10:01

josefx


You can't extend Enum like that. It's built in to the compiler, or the runtime (not sure which).

But it looks like you're trying to solve the wrong issue; the ordinal of an enum value is not supposed to have any functional meaning. As soon as you give it one, it should have a different name than 'Ordinal'. Your second code snippet is far superior to your first one.

In general, relying on ordinal for anything is bad practice; it probably never should've been exposed in the first place. The only thing you can rely on is the name, and any value you assign yourself.

If it's that important to you to name your field 'ordinal', just use the typesafe enum pattern (item 21), which Enum is just an implementation of.

like image 193
Joeri Hendrickx Avatar answered Jan 05 '23 10:01

Joeri Hendrickx