Enums in Java
Define type-safe constants with enums, add fields and methods to enum values, use EnumSet and EnumMap, and leverage enums in switch expressions.
Enum Basics
1. What is an Enum?
An enum is a special class that represents a fixed set of named constants. It prevents invalid values that plain `String` or `int` constants would allow.
2. Enum in switch
Enums work perfectly with switch — the compiler warns you if you miss a case (especially with switch expressions).
3. Iterating & Parsing Enums
`values()` returns all constants as an array. `valueOf(String)` converts a string to the matching enum constant.
Enum with Fields & Methods
1. Enum with Fields
Each enum constant can carry data. Declare fields and a constructor — the constructor is implicitly private.
2. Enum with Abstract Methods
Each enum constant can override an abstract method to provide its own behaviour.
EnumSet & EnumMap
1. EnumSet
`EnumSet` is a highly efficient `Set` implementation for enums. Internally uses bit flags — faster and less memory than `HashSet`.
2. EnumMap
`EnumMap` is a `Map` whose keys are enum constants. Faster and more memory-efficient than `HashMap` for enum keys.