Curriculum
In Java, an enum is a special type of class that represents a fixed set of constants. An enum can be used to define a set of values that are mutually exclusive and have a known and finite set of possible values. Enums are useful when you need to represent a fixed set of values that are known at compile time and you want to avoid using magic numbers or hard-coded strings in your code.
Here’s an example of an enum in Java:
public enum DayOfWeek { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY }
In this example, we define an enum called DayOfWeek
that represents the days of the week. Each value in the enum represents a day of the week, and is defined as a constant.
We can use this enum in our code by referencing its values directly, like this:
DayOfWeek today = DayOfWeek.MONDAY; System.out.println("Today is " + today);
This code creates an instance of the DayOfWeek
enum and assigns it the value MONDAY
. We then print out a message to the console that includes the value of the today
variable.
Enums in Java can also have additional methods and fields, just like any other class. Here’s an example:
public enum Color { RED("#FF0000"), GREEN("#00FF00"), BLUE("#0000FF"); private String hexValue; Color(String hexValue) { this.hexValue = hexValue; } public String getHexValue() { return hexValue; } }
In this example, we define an enum called Color
that represents a set of colors. Each value in the enum has an associated hexadecimal value, which is stored in a private field called hexValue
. We also define a constructor that takes a hex value as a parameter, and a getHexValue()
method that returns the hex value for a given color.
Overall, enums in Java are a useful way to represent a fixed set of constants that are known at compile time. By using enums, you can make your code more readable, maintainable, and easier to test.