Java enum type is a special type of class for creating a collection of constants.
Please note that enums implicitly extend java.lang.Enum. Since Java does not support multiple inheritance, an enum cannot extend anything else.
enum keyword is used for creating an enum.
enum LogLevel {
ERROR, WARN, INFO, DEBUG;
}
Enum valueOf
The valueOf() method can be used to obtain an instance of the enum class for a given String value.
LogLevel level = LogLevel.valueOf(“ERROR”);
Enum values are compared using ==
LogLevel level = LogLevel.valueOf(“ERROR”);
if(level == LogLevel.ERROR){
System.out.println(“It is an error log”);
}
We can define constructor , fields and methods for an enum just like normal classes. Please note that the constructor of enum can only be private and enum constants can only be created inside Enums itself.
Let us look into the below codes for better understanding of enum.
Enum with constructor and method
Output
ordinal() method returns the order of an enum instance.
values() method returns an array of Enum values. In the below example, Fruit.values() returns the array of enums defined in Fruit.
Enum with instance variable
Output
Enum in switch
Output