Vous êtes sur la page 1sur 2

Enumerated Types

There are some special variables that can take a value within a fixed set of constants. Since they
are constants, their names must be in uppercase letters, and an Enumerated types are declared
using the enum keyword. It should be used whenever the need to represent a fixed set of
constants arises.
Example:
In order to specify a days-of-the-week enum type
public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}
Here is some code that shows you how to use the Day enum defined above:
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;

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;
}
}

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();

}
This would consequently print out the following message:
Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.

Enumerated constants can be declared with values. You need to define a member variable and
a constructor, which must be private. Now to get the value associated with each coin you can
define a public getValue() method inside a java enum like any normal java class. Remember that
enum constants are implicitly static and final and cannot be changed once created.
Example:
public enum Currency {
PENNY(1), NICKLE(5), DIME(10), QUARTER(25);
private int value;

private Currency(int value) {
this.value = value;
}
}

There are important Enumerated methods available at our disposal, which also implicitly extend
java.lang.Enum. Here are three common methods:
equals() is used to compare enum constants for equality
compareTo() is used to compare the order of enum constants. The order of the constants is
the order of their declaration in the enum type.
ordinal() returns the position of the constant in the enumerated declaration