java.lang.Enum
class is the base class for all Java enums.
- It is an abstract base class and a direct child class of
java.lang.Object
Declaration:
public abstract class Enum
extends Object
implements Comparable, Serializable
Methods:
1) <b>values()</b>
method:
Every enum implicitly contains a static method (generated by the compiler) named
values()
that lists out all the values of enum in the order they have been declared.
Example:
Move[] m = Move.values();
for( Move m1 : m )
System.out.println( m1 );
Output:
LEFT
RIGHT
UP
DOWN
2) <b>ordinal() method</b>
:
The
ordinal()
method returns the ordinal value of an enumeration constant (i.e., its position in the enum declaration and the initial constant is implicitly assigned an ordinal of zero).
Declaration:
public final int ordinal()
The following example demonstrates
ordinal()
method:
Move[] m = Move.values();
for( Move m1 : m )
System.out.println( m1 + "-----" + m1.ordinal() );
Output:
LEFT-----0
RIGHT-----1
UP-----2
DOWN-----3
How is Java enum different from other languages?
- Unlike other languages, we can define normal variables, methods and constructors in a Java enum, which makes Java more powerful in this aspect.
- In addition to constants, if we define any extra members like methods and variables, then the list of constants must be in the first line and must end with a semicolon.
Example:
enum Bat
{
MRF, ADIDAS; //; is mandatory as we have a method after constants
public void fun()
{
\\ fun() body
}
}
- If we have extra members in an enum, either a list of constants or a semicolon is mandatory.
Example: This is invalid
enum Bat
{
public void fun(){}
}
But this is valid.
enum Bat
{
;
public void fun(){}
}
NOTE: An empty enum is valid.
Enum Bat
{
}
enum vs. Inheritance
- Every enum in Java is always a direct child class of
Java.lang.Enum
, which means we cannot extend any other enum.
- Every enum is always
final
implicitly. Hence we can’t create a child enum.
- Hence we can conclude that inheritance concept is not applicable for enum explicitly.
- But an enum can implement any no. of interfaces simultaneously.
Example:
enum A
{
// enum constants
}
enum B extends A // Can’t create a child enum
{
}
enum A extends java.lang.Enum
We can’t explicitly mention the fact that our enum extends
java.lang.Enum
// This is valid
interface C
{
// constant and method declarations
}
enum D implements C
{
}
// This is not valid
enum X
{
}
public class Y extends X
{
}
Compilation Error 1: enum types are not extensible
Compilation Error 2: cannot inherit from final X
- Declare an empty enum and try to compile the program.
- Declare an enum
Bats
with a method fun()
and some constants. Try to compile the program by having those constants after the method fun().