Enum can be considered to be syntax sugar for a sealed class that is instantiated only a number of times known at compile-time to define a set of constants.
A simple enum to list the different seasons would be declared as follows:
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
While the enum constants don’t necessarily need to be in all-caps, it is Java convention that names of constants are entirely uppercase, with words separated by underscores.
You can declare an Enum in its own file:
/**
* This enum is declared in the Season.java file.
*/
public enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
But you can also declare it inside another class:
public class Day {
private Season season;
public String getSeason() {
return season.name();
}
public void setSeason(String season) {
this.season = Season.valueOf(season);
}
/**
* This enum is declared inside the Day.java file and
* cannot be accessed outside because it's declared as private.
*/
private enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
}
Finally, you cannot declare an Enum inside a method body or constructor:
public class Day {
/**
* Constructor
*/
public Day() {
// Illegal. Compilation error
enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
}
public void aSimpleMethod() {
// Legal. You can declare a primitive (or an Object) inside a method. Compile!
int primitiveInt = 42;
// Illegal. Compilation error.
enum Season {
WINTER,
SPRING,
SUMMER,
FALL
}
Season season = Season.SPRING;
}
}
Duplicate enum constants are not allowed:
public enum Season {
WINTER,
WINTER, //Compile Time Error : Duplicate Constants
SPRING,
SUMMER,
FALL
}
Every constant of enum is public
, static
and final
by default. As every constant is static
, they can be accessed directly using the enum name.
Enum constants can be passed around as method parameters:
public static void display(Season s) {
System.out.println(s.name()); // name() is a built-in method that gets the exact name of the enum constant
}
display(Season.WINTER); // Prints out "WINTER"
You can get an array of the enum constants using the values()
method. The values are guaranteed to be in declaration order in the returned array:
Season[] seasons = Season.values();