Java Enum Inherit Enum
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 {//from w ww .j a va 2 s. c om
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 ww . ja va 2 s . c om*/
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.
Home »
Java Tutorial »
Java Data Type »
Java Tutorial »
Java Data Type »