enum type Inherit Enum

All enum inherit java.lang.Enum. java.lang.Enum's methods are available for use by all enumerations.

You can obtain a value that indicates an enumeration constant's position in the list of constants. This is called its ordinal value, and it is retrieved by calling the ordinal( ) method:


final int ordinal( )

It returns the ordinal value of the invoking constant. Ordinal values begin at zero.

You can compare the ordinal value of two constants of the same enumeration by using the compareTo( ) method.


final int compareTo(enum-type e)

enum-type is the type of the enumeration, and e is the constant being compared to the invoking constant.

If the two ordinal values are the same, then zero is returned. If the invoking constant has an ordinal value greater than e's, then a positive value is returned.

You can compare for equality an enumeration constant with any other object by using equals( ).

Those two objects will only be equal if they both refer to the same constant, within the same enumeration.

The following program demonstrates the ordinal( ), compareTo( ), and equals( ) methods:

 
// Demonstrate ordinal(), compareTo(), and equals(). 
enum Direction {
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {
    Direction ap, ap2, ap3;
    // Obtain all ordinal values using ordinal().
    for (Direction a : Direction.values()){
      System.out.println(a + " " + a.ordinal());      
    }
    ap = Direction.West;
    ap2 = Direction.South;
    ap3 = Direction.West;
    System.out.println();
    // Demonstrate compareTo() and equals()
    if (ap.compareTo(ap2) < 0)
      System.out.println(ap + " comes before " + ap2);
    if (ap.compareTo(ap2) > 0)
      System.out.println(ap2 + " comes before " + ap);
    if (ap.compareTo(ap3) == 0)
      System.out.println(ap + " equals " + ap3);
    System.out.println();
    if (ap.equals(ap2))
      System.out.println("Error!");
    if (ap.equals(ap3))
      System.out.println(ap + " equals " + ap3);
    if (ap == ap3)
      System.out.println(ap + " == " + ap3);
  }
}
  
Home 
  Java Book 
    Language Basics  

enum:
  1. enum type
  2. values( ) and valueOf( ) Methods
  3. enum as Class
  4. enum type Inherit Enum
  5. Overriding toString() to return a Token constant's value
  6. Assign a different behavior to each constant.