Java Enum Type

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Enum

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and WEST) etc. The java enum constants are static and final implicitly. It is available from JDK 1.5.

Java Enums can be thought of as classes that have fixed set of constants.

Points to remember for Java Enum
  • enum improves type safety

  • enum can be easily used in switch

  • enum can be traversed

  • enum can have fields, constructors and methods

  • enum may implement many interfaces but cannot extend any class because it internally extends Enum class

Simple example of java enum

What is the purpose of values() method in enum?

The java compiler internally adds the values() method when it creates an enum. The values() method returns an array containing all the values of the enum.

Internal code generated by the compiler for the above example of enum type

The java compiler internally creates a static and final class that extends the Enum class as shown in the below example:

Defining Java enum

The enum can be defined within or outside the class because it is similar to a class.

Java enum example: defined outside class

Java enum example: defined inside class

Initializing specific values to the enum constants

The enum constants have initial value that starts from 0, 1, 2, 3 and so on. But we can initialize the specific value to the enum constants by defining fields and constructors. As specified earlier, Enum can have fields, constructors and methods.

Example of specifying initial value to the enum constants

Constructor of enum type is private. If you don't declare private compiler internally creates private constructor.

Internal code generated by the compiler for the above example of enum type

Can we create the instance of enum by new keyword?

No, because it contains private constructors only.

Can we have abstract method in enum?

Yes, ofcourse! we can have abstract methods and can provide the implementation of these methods.

Java enum in switch statement

We can apply enum on switch statement as in the given example:

Example of applying enum on switch statement