Info |
---|
In Java, an enumeration is a special type of class that represents a group of related constants. An enumeration defines a set of named values that are represented by unique identifiers. The values of an enumeration are fixed at compile time and cannot be changed at runtime. |
Panel | ||||||||
---|---|---|---|---|---|---|---|---|
| ||||||||
Enumeration, often referred to as "enum" in programming, is a way to create a custom type that consists of a set of named constants. Here's a simple explanation:
Enums are a useful way to group and manage sets of related constants under a single umbrella. They make your code more understandable and less prone to errors caused by using incorrect or invalid values. |
To create an enumeration in Java, you define a new class that extends the Enum
class and defines a set of named constants as public static final fields. For example:
...
Code Block | ||
---|---|---|
| ||
/**
* This program demonstrates an enumerated type.
* Book Example
*/
public class Demo6
{
// Declare the Day enumerated type.
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY }
public static void main(String[] args)
{
// Declare a Day variable and assign it a value.
Day workDay = Day.WEDNESDAY;
// The following statement displays WEDNESDAY.
System.out.println(workDay);
// The following statement displays the ordinal
// value for Day.SUNDAY, which is 0.
System.out.println("The ordinal value for " +
Day.SUNDAY + " is " +
Day.SUNDAY.ordinal());
// The following statement displays the ordinal
// value for Day.SATURDAY, which is 6.
System.out.println("The ordinal value for " +
Day.SATURDAY + " is " +
Day.SATURDAY.ordinal());
// The following statement compares two enum constants.
if (Day.FRIDAY.compareTo(Day.MONDAY) > 0)
System.out.println(Day.FRIDAY + " is greater than " +
Day.MONDAY);
else
System.out.println(Day.FRIDAY + " is NOT greater than " +
Day.MONDAY);
}
} |
...