Java Reference
In-Depth Information
Use the enum keyword to declare an enumeration. Just like classes, an enum is defi ned
in a source fi le with a .java extension, and all the rules of package names and directory
structures apply. For example, the following enumeration represents the four seasons:
1. public enum Season {
2. WINTER, SPRING, SUMMER, FALL
3. }
The Season enum is saved in a source fi le named Season.java , and the compiled
bytecode is in a fi le named Season.class . Enumerations have the following properties:
The enum keyword actually defines a class behind the scenes that extends java.lang
.Enum . Therefore, an enum cannot extend any other class or enum.
You do not instantiate an enum. The constants defined in an enum are all implicitly
public , final , and static , so there is no reason to create instances of the enum class.
The enum can declare methods and additional fields. These additional fields and
methods must appear after the enum list, and the enum list must end with a semicolon
in this situation.
Because the elements of an enum are static, you can access them using the name of the
enum. Behind the scenes, the compiler writes a class that extends Enum and creates an
instance of the class for each element in the enum. This generated class contains a static
fi eld for each element in the enum.
The following code demonstrates the syntax for accessing enum elements. Study the
code and try to determine its output:
5. Season now = Season.WINTER;
6. switch(now) {
7. case WINTER :
8. System.out.println(“It is cold now”);
9. break;
10. case SUMMER :
11. System.out.println(“It is hot now”);
12. break;
13. default:
14. System.out.println(“It is nice now”);
15. }
You can declare variables of an enum type. The now variable on line 5 is of type Season
and is assigned to Season.WINTER . The case on line 7 is true, so the output of the preceding
code is
It is cold now
Search WWH ::




Custom Search