Java Enum - The Coding Shala
Home >> Learn Java >> Java Enum
Java Enum is a special type of data type. Enum is used to make collections of constants. It can be used for days of the week or directions or solar system etc. The java enum is final static implicitly. When we define Java enum it creates a class of type enum so we can define java enum inside the class or outside the class it doesn't matter. Java enum can have fields, constructors and methods.
Note: Constructors of the enum is always private. if we don't make it private java compiler make private constructor by defaults.
Java enum can be easily used with if-else or switch statements. we can traverse through enum easily. we can't create a new instance of enum because of its private constructor. Enum may implement interfaces but cannot extend any class because it internally extends Enum class.
The below example shows how to define enum and assign value to an enum type-
We can easily iterate through an enum variable, we use .value() that returns the list of values of an enum. the following is an example of this-
we can also use enum in an if-else statement and switch statement. The following example explains this-
As we know enum can have Constructor(private) and methods also. we also can initialize specific values to the enum constants. The enum constants have initial values that start from 0, 1, 2 and so on. Let's take an example of enum that contains constructors, methods, and values.
Enum class is available in java.lang.Enum and values(), ordinal(), valueOf() methods present in this.
- ordinal() method used to return index of enum constant.
Other Posts You May Like