Java Magazine, March/April 2016
ORACLE COM JAVAMAGAZINE MARCH APRIL 2016 42 new to java What Really Is an Enum Some people use enums only as described here and think of them as similar to int constants named values that can be assigned and recognized later But this is not the complete truth and if you stop here you have only scratched the surface and are missing out on some of the best features Enum declarations are full classes and the values listed are constant names referring to separate instances of these classes The enum declaration can contain fields constructors and methods just like other classes Here is an extended version of the previous enums public enum CommandWord GO go LOOK look TAKE take HELP help QUIT quit private String commandString CommandWord String commandString this commandString commandString public String toString return commandString The important aspects are the following Enum declarations are classes and enum values refer to objects For every declared enum value an instance of the class is created and assigned to that value No other instances of this class can be created later Every different enum value will refer to a diferent object and the same value will always refer to the same object this cannot be changed Enums create their own namespace so diferent enum classes may use the same value but these are kept separate If for example I have an enum class BoardGames the enum values BoardGames GO and CommandWords GO are separate and do not interfere with each other The last aspect that no other instances may be created is ensured by making the constructor private It is not necessary to declare this explicitly the constructor is automatically private and it is an error to try to make it public The previous code will generate five enum objects one for each value And any reference in other code to CommandWord objects can be to only one or more of these enums Any attempt to create other objects will generate a compiletime error Enums may contain any number of fields constructors and methods The fundamental diference when compared with normal classes is in how enum instances come into existence While other classes start without any instances and provide a constructor for clients to create as many objects as they like enums provide no constructor to the outside and instead provide a set of ready made instances The fact that enum values are objects not ints is important It means that enums provide not only identity but also state and behavior The Full Truth The first question that now comes to mind is this If the constructor cannot be called from the outside what is it used for The answer lies in the modified syntax we have used for enumerating our enum values Instead of just GO as in our first version we have now written GO go
You must have JavaScript enabled to view digital editions.