INTRODUCTION
An enum type in Java is a special data type that is defined whenever you need to define a variable with a set of predefined values such as Days of the Week, Months of the Year, items in a menu, etc.
KEY POINTS ABOUT ENUM
- An enum type variable is defined using the keyword enum.
- All values in the set of predefined values must be in uppercase letters.
- A variable with the type enum must be equal to one of the values from the set of constants predefined for it.
- The enum class contains a static values method that returns an array of constants in the same order as they were declared in the enum type.
- All enum variables extend the java.lang.Enum class by default.
- Enums are final by default.
- Whenever you define fields and methods as part of the enum class, the definition of the list of the enum constants must end with a semicolon.
- Enums declared within a class are static by default.
- Enum class constructors are always private. Hence, they cannot be instantiated.
- Enums are all singletons and hence, can be compared for equality using == operator.
EXAMPLE
Let us take a simple example to demonstrate the functionality of enum.
public enum Month {
JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER
}
Please refer to the code below to see how the enum type Month is used:
public class EnumExample {
Month month;
public EnumExample( Month month) {
this.month = month;
}
public void festivalsRoundTheYear() {
switch (month) {
case JANUARY:
System.out.println("Happy New Year!");
break;
case MARCH:
System.out.println("Happy Holi!");
break;
case NOVEMBER:
System.out.println("Happy Diwali!");
break;
case DECEMBER:
System.out.println("Merry Christmas!");
break;
default:
System.out.println("No festivities.");
break;
}
}
public static void main(String[] args) {
EnumExample janMonth = new EnumExample(Month.JANUARY);
janMonth.festivalsRoundTheYear();
EnumExample marchMonth = new EnumExample(Month.MARCH);
marchMonth.festivalsRoundTheYear();
EnumExample novMonth = new EnumExample(Month.NOVEMBER);
novMonth.festivalsRoundTheYear();
EnumExample decMonth = new EnumExample(Month.DECEMBER);
decMonth.festivalsRoundTheYear();
EnumExample juneMonth = new EnumExample(Month.JUNE);
juneMonth.festivalsRoundTheYear();
}
}
The output is:
Happy New Year!
Happy Holi!
Happy Diwali!
Merry Christmas!
No festivities.
0 Comment(s)