Is there any difference between this declaration
Thread.State state = Thread.State.NEW;
and that
Enum<Thread.State> state = Thread.State.NEW;
in Java? Instead of the second option is a bit longer?
Is there any difference between this declaration
Thread.State state = Thread.State.NEW;
and that
Enum<Thread.State> state = Thread.State.NEW;
in Java? Instead of the second option is a bit longer?
It's the same case as comparing between:
Child o = someChild;
and
Parent o = someChild;
Enum
is the parent class of all enum types. Therefore, with the second line, the code cannot contain references to specific members of Thread.State
, specifically the members described in this section of the language spec.
Is there any difference ....
In practice, in this particular case, probably no.
In theory, Thread.State
is a subtype of Enum<Thread.State>
. If Thread.State
declared (non-private) fields or methods, then you could use them via the first declaration of state
, but not the second one.
In general, the first form is preferable ... for that reason.
Also, I don't think you would be able to see an enum's static
methods values()
and valueOf
via the variable declared in the second declaration; e.g.
state.valueOf("BLOCKED")
However, calling a static method via an instance reference is bad style.
Two practical differences (as opposed to language-lawyerly reasons) that come to mind:
state
as an Enum<Thread.State>
, then you won't be able to pass it to any methods that expect a Thread.State
.state
as an Enum<Thread.State>
, you'll leave the reader — whoever needs to touch this code in the future — wondering why you've written it that way.Neither of these is a terribly deep reason; we could easily imagine a parallel universe where most people used Enum<Thread.State>
instead of Thread.State
, just as (in our universe) most people use List<...>
instead of ArrayList<...>
(when possible). But since most people don't do that in our universe, you're better off just following the common pattern, to minimize the risk of confusion and accidental incompatibility.
Incidentally, in case this is going to be your next question . . . the main situation where you would use Enum
is when you want to write something generic that works for many different enum types. An example of this in the JDK is EnumMap<K extends Enum<K>,V>
, which is a special map implementation that gets space and performance benefits out of knowing that its keys are enum values.
(And note, incidentally, that you can't write EnumMap<Enum<Thread.State>, String>
, because Enum<Thread.State>
doesn't extend Enum<Enum<Thread.State>>
. Instead, you must write EnumMap<Thread.State, String>
. So this is an example of difference #1 that I mentioned above: if you declare state
as an Enum<Thread.State>
, then you can't use it as a key in an enum-map.)