Enum, Enum Types or Enumeration are special data types in JAVA, which are used to represent similar kind of constants. For example
Months (JANUARY, FEBRUARY, MARCH, APRIL . . . )
Days (MON, TUES, WED . . .)

Key Points

  • It is not mandatory but best practice to declare Enum constants with UPPERCASE letters unlike any other constant in JAVA.
  • Enum are mainly used when we want to have limited set of values, which remain constant and we know about all possible values at compile time. For example, choices on a menu or options of a combo-box.
  • ordinal() method is used get the order of an enum constant in an enum type
  • Enum types can be defined outside a class (inside own file) or inside a class but not inside a method or block
  • Enum are type-safe by nature and they provide type-safety during compilation. That means it gives compile time error if we try to assign any values other than the specified Enum
  • Compiler generates a .class file for each Enum constant while compilation.
  • Enum can have any number of static as well as instance initialization blocks.
  • java.lang.Enum implements Comparable and Serializable interface, as a result all enum are Comparable and Serializable by default.
  • We can compare the enum constants using == operator, as these are constant and does not change while execution.
  • We can retrieve the constants of any enum using values() method. It returns an array of Enum constants.
Basic Enum Definition

Enum Body

Enum constants can have their own body called Constant Specific Body. In that body, we can define attributes and methods, but these are visible within the Constant Specific Body in which they are defined.
Constant Specific Body

Unlike Class

  • Unlike any class in Java Enum types can have attributes, constructors and methods along with Enum constants.
  • Constructors are private by default and only private or package private constructors are allowed in Enum types. As a result we can’t instantiate Enum types using new operator.
  • Enum constants are created only once (Singleton) for the whole execution. All enum constants are created when we refer any enum constant first time in the code or load Enum class. As a best practice we should create each attribute in Enum as final to avoid unexpected behavior.
  • Enum constants must be declared first ahead of attributes, constructors or methods
Example

Inheritance

  • All enum types extend java.lang.Enum class by default. As a result they can’t extend any other classes
  • Enum types can implement any number of interfaces unlike any Java class
  • Enum types are final by default. They can not be extended by any other type or class.