Enumerated Types in Java Programming

Enumerated Types in Java Programming

Previous Home Next

 

An enumerated type is a type whose fields consist of a fixed set of constants. Common examples include the days of the week and the months of the year.

You should use enumerated types any time you need to represent a fixed set of constants.
 That includes natural enumerated types such as the planets in our solar system,months in the year
 and data sets where you know all possible values at compile time—for example, the choices on a menu.
 In the Java programming language, you define an enumerated type by using the Enum keyword.

for example you would specify suit of the playing cards.

public enum suit
{
club ,diamond ,heart ,spade
}


 
public class EnumTests {
Day day;

public EnumTests(Day day)
{
this.day = day;
}

public void ItLikeItIs()
{
switch (day)
{
case MONDAY: System.out.println("Mondays are good to start.");
break;

case FRIDAY: System.out.println("Fridays are good.");
break;

case SATURDAY:
case SUNDAY: System.out.println("Weekends are best.");
break;

default: System.out.println("Midweek days are boring.");
break;
}
}

public static void main(String[] args) {
EnumTest firstDay = new EnumTest(Day.MONDAY);
firstDay.ItLikeItIs();
EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
thirdDay.ItLikeItIs();
EnumTest fifthDay = new EnumTest(Day.FRIDAY);
fifthDay.ItLikeItIs();
EnumTest sixthDay = new EnumTest(Day.SATURDAY);
sixthDay.ItLikeItIs();
EnumTest seventhDay = new EnumTest(Day.SUNDAY);
seventhDay.ItLikeItIs();


}
}


Previous Home Next