Java Enum
Java Enum
Java Enums can be thought of as classes which have a fixed set of constants (a variable
that does not change). The Java enum constants are static and final implicitly. It is
available since JDK 1.5.
Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it
can implement many interfaces. We can have fields, constructors, methods, and main
methods in Java enum.
{ {
JAN,FEB,MAR, ……, DEC; KF,KO,RC,FO;
} }
enum Beer{
KF, KO, RC, FO;
}
class Test {
public static void main(String[] args) {
1
Beer b=Beer.KF;
System.out.println(b);
}
}
Note: we can declare enum outside the class or inside the class and also inside the
main method.
If we declare enum outside the class, then applicable modifiers are:
public, default and strictfp.
If we declare enum within the class, then applicable modifiers are:
private, protected and static. along with (public, default and strictfp).
2
case RC: System.out.println(“it is a KF brand”);
break;
default: System.out.println(“Invalid Option”);
}
}
}
Note: if we take enum type argument in the switch statement then every case label
should valid enum constant. Or else it will give compile time error.
enum vs inheritance
Every enum in java is a direct child class of java.lang.Enum class.
Hence, we cannot extend any other class.
Every enum is final implicitly hence, we cannot create child enum class.
values ()
Every enum implicitly contains values() method to return all values present inside the
enum.
ordinal ()
The order of every constant present in the enum are important thus we can represent
this order by using ordinal() method.
Ordinal means indexes of all the constant. It starts from 0. Index of array is equal to
ordinal of enum.
enum Beer {
KO, FO, KF, RC;
}
class Test{
public static void main(String[] args){
Beer[] b=Beer.values();
for(Beer b1 : b){
3
System.out.println(b1+“…….”+b1.ordinal());
}
}
}
Speciality of Java enum
In old language enum, we can declare only constant. But in java enum in
addition to constant we can also declare methods, constructors and normal
variables etc.
Hence java enum is more powerful than old language enum.
Even we can declare main() method inside the enum. Hence we can invoke
directly from the command prompt.
If we are declaring any extra member like methods, constructors then list of the
constant should be in the first line and should ends with semi colon (;).
enum Month
{
;
public void m1{}
}
enum vs Constructor
enum can contains constructor and it is executed separately for every enum constant at
the time of enum class loading.
4
enum Beer {
KO, FO, KF, RC;
Beer {
System.out.println(“constructor”);
}
}
class Test{
public static void main(String[] args){
Beer b=Beer.KF;
System.out.println(“Hello”);
}
}
}