enum in Java

1. Introduction

An enum type enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. You should use enum type when you need to represent a fixed set of constants and you know all possible values are compile time. Common examples include days of the week, planets in our solar system and months in a year.

2. Define an enum type

You define an enum type by using the enum keyword. For example:

public enum Day {

3. Important points

  • enum type was introduced in Java 1.5.
  • Inside enum type methods, variables and constructor can be declared only after list of constants.
  • Since enum is a keyword, we can’t end package name with it, for example com.learnitweb.enum is not a valid package name.
  • According to Java naming conventions, it is recommended that we name constant with all capital letters.
  • The enum declaration defines a class (called an enum type). Java enum types are much more powerful than enum types in other languages as enum class body in Java can include methods and other fields as well.
  • All enum implicitly extend java.lang.Enum. Since a class can only extends one parent, an enum cannot extend anything else.
  • An enum can implement interfaces.
  • Internally enum is implemented by using class. Every enum constant is a reference variable to that enum type object. Every enum constant is implicitly public static final. Since enum constant is final, we can’t create child enum type.
  • Since enum is represented as a class and can contain methods, we can define main method in enum. Hence we can invoke main method from command prompt.
  • You cannot manually invoke an enum constructor. The constructor for an enum type must be package-private or private access. So you cannot create an instance of enum using the new operator.
  • An enum type cannot be declared inside a method.
  • enum can contain both concrete methods and abstract methods. If an enum class has an abstract method, then each instance must implement it.

4. Important methods

  • public static T[] values() – returns all the constants of the enum type.
  • public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) – Returns the enum constant of the specified enum type with the specified name.
  • int ordinal() – Returns the ordinal(position) of this enumeration constant in its enum declaration, where the initial constant is assigned an ordinal of zero.