Aug
11
2016
By abernal
Enums are classes
That represents an enumeration which is like a fixed set of constants.
- Provides type-safe checking
- Is impossible to create an invalid enum type without a compile error
A good example for enums are
- Days of the week
- Months of the year
- The cards in a deck
Sample
public enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
Usage
Day day = Day.TUESDAY; System.out.println(Day.MONDAY.); // MONDAY System.out.println(s == Day.WEDNESDAY); // false
Within a loop
for(Day day: Day.values()) { System.out.println(day.name() + " " + day.ordinal() ); }
Output
MONDAY 0
TUESDAY 1
WEDNESDAY 2
THURSDAY 3
FRIDAY 4
SATURDAY 5
SUNDAY 6
Be aware of
if( Day.MONDAY == 0 ) {} // DOES NOT COMPILE
Enums are types and not int
Adding Constructors, Fields and Methods
public enum Season { WINTER("Low"), SPRING("Medium"), SUMMER("High"), FALL("Medium"); private String expectedVisitors; private Season(String expectedVisitors) { this.expectedVisitors = expectedVisitors; } public void printExpectedVisitors() { System.out.println(expectedVisitors); } }