J9a Enum type
Introduction to Programming 1 1
Enum
● An enum type is a type whose fields consist of a
fixed set of constants.
public enum Day { SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, SATURDAY }
Introduction to Programming 1 2
Example 1
public class EnumTest {
Day day;
public EnumTest(Day day) {
this.day = day;
}
public void tellItLikeItIs() {
switch (day) {
case MONDAY:
System.out.println("Mondays are bad.");
break;
Introduction to Programming 1 3
Example 1
case FRIDAY:
System.out.println("Fridays are better.");
break;
case SATURDAY:
case SUNDAY:
System.out.println("Weekends are best.");
break;
default:
System.out.println("Midweek days are so-
so.");
break;
}
}
Introduction to Programming 1 4
Example 2
● have a static values method that returns an array
containing all of the values
for (Day d : Day.values()) {
System.out.println("The day is:” +
d.toString());
}
Introduction to Programming 1 5
Example 3
● The enum class body can include methods and
other fields (not necessarily static)
● an enum cannot be instantiated
public class Main {
Day d;
enum Day { SUN,MON,TUES;
public boolean isMon(Day a) {
return (a==Day.MON);
}
}
Introduction to Programming 1 6
Example 3
public static void main(tring[] args) {
Main m = new Main();
Day d1 = m.d;
d1 = Day.TUES;
boolean ans = d1.isMon(d1);
}
}
Introduction to Programming 1 7