In Java, an enumeration (or enum) is a type that represents a fixed set of constants. Each constant in the enum is an instance of the enum type and has a name and a value. Enums can be used to define a set of related constants, such as the days of the week or the months of the year.
Here is an example of how to define and use an enumeration in Java:
public enum Day {
MONDAY,
TUESDAY,
WEDNESDAY,
THURSDAY,
FRIDAY,
SATURDAY,
SUNDAY
}
public class MyClass {
public static void main(String[] args) {
Day today = Day.TUESDAY;
System.out.println("Today is " + today);
}
}
In this example, we define an enumeration called Day that represents the days of the week. We then declare a variable today of type Day and assign it the value Day.TUESDAY. Finally, we print out the value of today.
Enums can also have methods and fields, just like regular classes. Here is an example of how to define an enum with methods:
public enum Coin {
PENNY(1),
NICKEL(5),
DIME(10),
QUARTER(25);
private final int value;
private Coin(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
public class MyClass {
public static void main(String[] args) {
Coin coin = Coin.NICKEL;
System.out.println("The value of a nickel is " + coin.getValue() + " cents.");
}
}
In this example, we define an enumeration called Coin that represents US coins. Each coin has a value, which is passed to its constructor. We also define a method getValue() that returns the value of the coin. In the main() method, we create an instance of Coin and call its getValue() method to get its value.
In summary, an enumeration in Java is a type that represents a fixed set of constants. Enums can be used to define a set of related constants and can have methods and fields, just like regular classes. Enums are useful for representing fixed sets of values that are known at compile time.