Enumerations in Java are similar to other ordinary classes in that they contain a set of pre-defined objects in their own right.
Here are a few examples of enumerations that can help us better use enumeration types;
A simple example
Package Simplejava; enum Color { // Each is a instance of Color}publicclass Q5 { Public Static void Main (string[] args) { for (Color color:Color.values ()) { System.out.println ( color); }}}
Result output:
RED
YELLOW
Blue Call construction method
PackageSimplejava;enumColor {RED (1), YELLOW (2), BLUE (3);//Each are an instance of Color Private intvalue; PrivateColor (inti) { This. Value =i; } Public voidPrintvalue () {System.out.println ( This. Value); }} Public classQ5 { Public Static voidMain (string[] args) { for(Color color:Color.values ()) {color.printvalue (); } }}
Results Print:
1
2
3 When to use enumerations
The enumeration in Java is similar to the normal class, and contains a set of predefined objects in the interior.
A better use case is to block invalid parameters. The following code example:
Public void dosomethingwithcolor (int color);
This is an ambiguous interface, and other developers simply do not know which parameters to pass to this interface, only the int type;
For example, if you have an enumeration type color that contains a collection of black,red two objects, then this interface becomes this:
Public void dosomethingwithcolor (color color);
The use of enumeration types will greatly enhance the readability of your code while preventing the passing of invalid parameters;
Link: http://www.programcreek.com/2014/01/java-enum-examples/
"Simple Java" Java enumeration example