An enum is a specialized “class” designed to represent a collection of constants, akin to unchangeable variables such as final variables.
To define an enum, utilize the enum keyword (as opposed to class or interface), and delineate the constants with commas. It’s essential to denote the constants in uppercase letters.
enum |
Enum constants can be accessed using the dot syntax.
Level myVar = Level.MEDIUM; |
Enum is short for “enumerations”, which means “specifically listed”. |
It is also possible to include an enum within a class.
public
|
The output would be:
MEDIUM |
Enums are commonly utilized in switch statements to verify matching values.
enum
|
The output will be:
Medium level |
The enum type includes a values() method, which yields an array containing all enum constants. This method proves handy when iterating through the constants of an enum.
for |
The result will be:
|
Difference between Enums and ClassesAn enum, akin to a class, can possess attributes and methods. The key distinction lies in the fact that enum constants are inherently public, static, and final (immutable and cannot be overridden). Enums cannot instantiate objects, nor can they extend other classes (although they can implement interfaces). Why And When To Use Enums?Employ enums for values expected to remain constant, such as days of the week, colors, deck of cards, etc. |