Previous | Home | Next |
Enum is a keyword which enum type is a special data type used to define collections of constants. A Java enum type is a special kind of Java class. An enum can contain constants, methods etc. Java enum were added in Java 5. For example Number of days in Week. Enum constants are implicitly static and final and you can not change there value once created. Notice curly braces around enum constants because Enum are type like class and interface in Java. similar naming convention for enum like class and interface (first letter in Caps) and since Enum constants are implicitly static final we have used all caps to specify them like Constants in Java. The names of an enum type's fields are in uppercase letters.
In the Java programming language, you define an enum type by using the enum keyword.
Syntax :
public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
The enum keyword which is used in place of class or interface.
Example :
public class EnumTest { public enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Day day; public EnumTest(Day day) { this.day = day; } public void tellItLikeItIs() { switch (day) { case MONDAY:System.out.println("Mondays are bad."); break; case FRIDAY:System.out.println("Fridays are better."); break; case SATURDAY:System.out.println("Weekends are best."); break; case SUNDAY:System.out.println("Weekends are best."); break; default:System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args) { EnumTest firstDay = new EnumTest(Day.MONDAY); firstDay.tellItLikeItIs(); EnumTest thirdDay = new EnumTest(Day.WEDNESDAY); thirdDay.tellItLikeItIs(); EnumTest fifthDay = new EnumTest(Day.FRIDAY); fifthDay.tellItLikeItIs(); EnumTest sixthDay = new EnumTest(Day.SATURDAY); sixthDay.tellItLikeItIs(); EnumTest seventhDay = new EnumTest(Day.SUNDAY); seventhDay.tellItLikeItIs(); } }
output :
Mondays are bad. Midweek days are so-so. Fridays are better. Weekends are best. Weekends are best.
The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields.
All enums implicitly extend java.lang.Enum. Because a class can only extend one parent.
Previous | Home | Next |