Direct enum vs Enum<> .. What is the exact technical difference?

Viewed 54

Given the following enum:

public enum Letter {
    Alpha, Beta, Gamma, Delta;
}

Then both of the following compile without error:

Letter       letter1 = Letter.Alpha;
Enum<Letter> letter2 = Letter.Beta;

Calling getClass() or name() or ordinal() on both letter1 and letter2 shows the same results.

But! The following will compile:

switch( letter1 ) {
case Alpha:
case Beta:
}

While this will not:

switch( letter2 ) {
case Alpha:
case Beta:
}

So what, if any, is the exact technical difference between these two variables?

1 Answers

Letter is to Enum<Letter> as Integer is to Number. A subclass to a superclass. The only difference is that Enum<> is a privileged superclass that's related to a certain language feature. (See java.lang.Record for another such privileged superclass.)

If we have these two variables:

Integer n1 = 1;
Number  n2 = 2;

... then this works:

jshell> switch(n1) { case 1: System.out.println("one"); break; default: System.out.println("not one"); break;}
one

... but this does not:

jshell> switch(n2) { case 1: System.out.println("one"); break; default: System.out.println("not one"); break;}
|  Error:
|  incompatible types: java.lang.Number cannot be converted to int
|  switch(n2) { case 1: System.out.println("one"); break; default: System.out.println("not one"); break;}
|        ^--^

In both cases, the compiler can't prove (prior to runtime) that Number or Enum<Letter> is something it can switch on, so it won't let you do that.

Related