Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Enum<T> vs T as variable type

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?

like image 966
k13i Avatar asked Feb 25 '17 11:02

k13i


People also ask

Is enum type or class in Java?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables).

Is enum better than string?

They are type safe and comparing them is faster than comparing Strings. Save this answer. Show activity on this post. If your set of parameters is limited and known at compile time, use enum .

What are enum types in Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

Can enum have different types?

Enums have their own data type and each enum is essentially a new data type. This is where one of their their biggest powers lie - they can be strongly type checked at compile time. I have added further values to demonstrate the resultant versatility.


1 Answers

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.

like image 109
M A Avatar answered Oct 04 '22 00:10

M A