Java Object Oriented Design - Java Enum class

Superclass of an Enum Type

The compiler creates a class when an enum type is compiled.

An enum type can have constructors, fields, and methods. An enum type is instantiated only in the code generated by the compiler.

Every enum type implicitly extends java.lang.Enum class. All methods defined in the Enum class can be used with all enum types.

Enum class

The following table lists the methods that are defined in the Enum class.

  • public final String name()
    Returns the name of the enum constant.
  • public final int ordinal()
    Returns the order of the enum constant.
  • public final boolean equals(Object other)
    Returns true if the specified object is equal to the enum constant. Otherwise, it returns false. The == operator and the equals() method return the same result, when they are used on two enum constants.
  • public final int hashCode()
    Returns the hash code value for an enum constant.
  • public final int compareTo(E o)
    Compares this enum constant with the specified enum constant. It returns the difference in ordinal value of this enum constant and the specified enum constant.
  • public final Class getDeclaringClass()
    Returns the class object for the class that declares the enum constant.
  • public String toString()
    By default, it returns the name of the enum constant, which is the same as the name() method.
  • public static valueOf(Class enumType, String name) Returns an enum constant of the specified enum type and name. For example,


Level  lowLevel = Enum.valueOf(Level.class, "LOW")

The following code shows how to compare two enum constants:

enum Level {//from w ww. ja va  2s. c o  m

public class Main {
  public static void main(String[] args) {
    Level s1 = Level.LOW;
    Level s2 = Level.HIGH;

    // s1.compareTo(s2) returns s1.ordinal() - s2.ordinal()
    int diff = s1.compareTo(s2);
    if (diff > 0) {
      System.out.println(s1 + "  occurs after  " + s2);
    } else {
      System.out.println(s1 + "  occurs before " + s2);


The code above generates the following result.