In Java
an enumerated type is
a type that specifies a sequence of named constants. Not to mention that theses
constants are related. The days of week or months of year can be good examples
of enums. Prior to Java 5 Java developers had to use sets of named integer
constants to simulate enum type behavior. Starting with Java 5 the developers
got the built-in support of enums in Java.
An enum in Java is
an enumerated type that is declared with the reserved key word enum. Consider
the following piece of code:
enum DaysOfWeek {
FRIDAY,
SATURDAY,
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY
}
It is a convention to write enum members in Capital Letters.
Please note that unlike enumerated types in other languages like C++ and C#,
enums in Java are not integer based. They are pure classes. Each member of the
enum is a public static final field, representing an instance of its enum class.
Enum ensure compile-time type safety by preventing a developer from
assigning illegal values to an enum type. Consider the following piece of code:
enum DaysOfWeek {
FRIDAY,
SATURDAY,
SUNDAY,
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY
}
enum Fruits {
MANGO,
ORANGE,
APPLE,
BANANA,
APRICOT,
PINEAPPLE
}
DaysOfWeek today = Fruits.MANGO; //compile-time error
The above code would signal errors at compile time. Please note
that if the enums were int-based in Java the above could would have compiled
successfully. The fact that they are pure Java objects, prevented the above
code from compiling successfully.
The enums in Java, like other objects, provide a toString() method that returns a meaningful description of a constant’s
value.
No comments:
Post a Comment