In Java, enums are far more powerful than in other programming languages. Behind the scenes, an enum compiles down to a full class structure that extends java.lang.Enum. This means enums can have fields, constructors, and custom methods attached to each constant.
In this guide, we will look at how to construct advanced enums with custom property states and loop through their constants.
Imagine having a set of access keycards for rooms in a secure office building:
- Each card has a label constant: **WINTER**, **SPRING**, **SUMMER**, or **FALL**.
- In addition to the label, each card has custom values written on the back, such as the min temperature (e.g. 5 degrees) and max wind speed (e.g. 8 km/h).
- When you grab the **WINTER** card, you immediately know its specific temperature and speed properties.
1. Attaching Fields and Constructors to Enum Constants
Since enums are compile-time classes, you can define fields and a constructor inside them. Let's write an enum representing seasons with custom temperature limits:
enum Season4 {
WINTER(5, 8), SPRING(10, 9), SUMMER(15, 6), FALL(20, 2);
int value1, value2; // Custom fields for each constant
// Private Constructor
private Season4(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
}
- Always Private: The constructor of an enum must be
privateor package-private. You cannot call it manually using thenewkeyword. The JVM constructs the enum constants automatically at load time. - Initialization Lists: The list of enum constants (e.g.
WINTER(5, 8)) must be the first line of code in the enum. If you put fields or methods above the constants list, it will fail to compile.
2. Iterating Enum Values
Every Java enum automatically inherits a static method named values(). This method returns an array containing all the constants of that enum, preserving the order in which they were declared:
public class Enums_Constant {
public static void main(String args[]) {
// Iterate through all seasons
for (Season4 s : Season4.values()) {
System.out.println(s + " values: " + s.value1 + ", " + s.value2);
}
// Direct access
Season4 s1 = Season4.WINTER;
System.out.println("Winter limits: " + s1.value1 + " to " + s1.value2);
}
}
Conclusion
Java enums are powerful classes that allow you to bundle custom attributes and states directly onto constant declarations. Use them when constants represent objects with defined attributes (like status codes, sizing scales, or configuration configurations).