Enum in Java
Enumerations serve the purpose of representing a group of named constants in a programming language.
Enums are used when we know all possible values at compile time, such as choices on a menu, rounding modes, command lines flags, etc. It is not necessary that the set of constants in an enum type stay fixed for all time.
1. Important points of enum:
Every enum internally implemented by using Class:
Every enum constant represents an Object of type enum.
enum type can be passes as an argument to switch statement.
Every enum constant is always implicitly public static final. Since it is static, we can access it by using enum Name. Since it is final, we can't create child enums.
We can declare main() method inside enum. Hence we can invoke enum directly from the Command Prompt.
2. Enum and Inheritance:
All enums implicitly extend java.lang.Enum class. As a class can only extend one parent in Java, so an enum cannot extend anything else.
toString() method is overridden in java.lang.Enum class, which returns enum constant name.
enum can implement many interfaces.
2.1 values(), ordinal() and valueOf() methods:
These methods are present inside java.lang.Enum
values() method can be used to return all values present inside enum.
Order is important in enums. By using ordinal() method, each enum constant index can be found, just like array index.
valueOf() method returns the enum constant of the specified string value, if exists.
Last updated
Was this helpful?