Let us assume you have the need for some constants in your application; say the three primary colors: Red, Green, Blue. You could create a class specifically for holding the constants thus:
class PrimaryColorsStatic {
public static final String RED = "red";
public static final String GREEN = "green";
public static final String BLUE = "blue";
}
and any of these can be used:
PrimaryColorsStatic.RED or
PrimaryColorsStatic.GREEN or
PrimaryColorsStatic.BLUE
This would work, but it is very limited. Let say you want to hold, apart from the name, the hex code and rgb code of the color as part of the constant? How would this be done with the mechanism above? Whatever way you find to implement this would feel forced as static variables of classes were not designed to help fulfil such use cases.
Enum in Java provides a more robust mechanism for dealing with constant values in your application.
Enum can be formally defined as
a special data type that enables for a variable to be a set of predefined constants.
The basic syntax is simple. The primary color example can be represented as an Enum with the following code:
public enum PrimaryColorsEnum {
RED, GREEN, BLUE
}
[this means that the file would be saved as PrimaryColorsEnum.java]
and an example of accessing it would be:
public main void() {
PrimaryColorsEnum RedHolder = PrimaryColorsEnum.RED;
System.out.println(RedHolder);
}
This would print red to the console as a string.
Just knowing the above syntax and when to use it could get you by with Enum, but you have hardly scratched the surface with just that.
To fully appreciate Enums, let us take a step back and see if we can grok the concept in a more detailed level.