Java Enum Inherit Enum
In this chapter you will learn:
- enum type Inheriting Enum
- Ordinal value
- Example - Enum Ordinal value
- 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:
- How to use Java Enum compareTo
- Syntax for Java Enum compareTo
- Return value from Java Enum compareTo
- Example - compare the ordinal value of two constants of enum