Java Enum Inherit Enum

In this chapter you will learn:

  1. enum type Inheriting Enum
  2. Ordinal value
  3. Example - Enum Ordinal value
  4. Example - Overriding toString() to return a Token constant's value

Description

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

Ordinal value

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.

Example

Enum Ordinal value


enum Direction {/*w  ww . j  av  a2s  .  c o  m*/
  East, South, West, North
}

public class Main {
  public static void main(String args[]) {

    for (Direction a : Direction.values()){
      System.out.println(a + " " + a.ordinal());      
    }

  }
}

The code above generates the following result.

Example 2

Overriding toString() to return a Token constant's value.

 
enum Token {/*from w  w  w .ja v  a  2  s .com*/
  IDENTIFIER("ID"), INTEGER("INT"), LPAREN("("), RPAREN(")"), COMMA(",");
  private final String tokValue;

  Token(String tokValue) {
    this.tokValue = tokValue;
  }

  @Override
  public String toString() {
    return tokValue;
  }

}
public class Main{
  public static void main(String[] args) {
    for (Token t:Token.values()){
      System.out.println(t);      
    }
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to use Java Enum compareTo
  2. Syntax for Java Enum compareTo
  3. Return value from Java Enum compareTo
  4. Example - compare the ordinal value of two constants of enum
Home »
  Java Tutorial »
    Java Langauge »
      Java Enum
Java Enum type
Java Enum values() / valueOf() Methods
Java Enum as Class
Java Enum Inherit Enum
Java Enum compareTo
Java Enum equals
Java Enum Behaviour