Lesson: Enums

Overview: 
Explore Java enum (enumerations) class.
Objectives: 

Understand Java enum class and how to use it.

Content: 

An enum or enumeration, is a special data type (an object) defined by Java. It is a list of constant values known at compile time by name. When a variable of the enum type is created it is assigned one of it's pre-defined constant value names and can only have one it's pre-defined constant names as its value. Because they are constants, the names assigned are by convention in upper case. Here is an example:

The key concept is using names instead of numeric or string constant values, so instead of having to remember what 1 or 9 or whatever some number means when looking at the day of the week, you use a name. Using names improves readability and reliability of code by making things more obvious. So how do we use enums? Here are some examples:

Here we created a variable day of enum type DayOfWeek and set it to TUESDAY. We can then use day in various ways. enums are best used to represent a fixed set of constants, like day of week, planets of the solar system, menu choices, any list of constants whose values are all known at compile time. Internally, each enum name is assigned an int value starting at zero, but in the simple enum case, we don't care as we want to use the names not numbers.
 
To make things more interesting, remember that an enum  is a special form of a class. Therefore it can have fields and methods. By default, enum variables won't tell you their underlying value, only the name. We can extend the enum in the above example to track and return the underlying value of the enum to demonstrate extending the enum with fields and methods:

Here we added an int field to the enum and defined a constructor to set the value of the field. We also added a method to get the day number and made the field public so we can access it directly. Note that when using a constructor, we are required to explicitly define the constants for each name. Note in this example the numeric values assigned to the enum names are not in sequence. They don't have to be. You can assign any value you wish to the names. You can use any data type for the values assigned to the names. You can also create more than one field so that an enum can contain more than one data item.
 
Enums are very useful in their basic form and given that they have the full capability of classes, they can be extended to be very powerful.
 
Here is a video about enums. Here is a detailed discussion of enums.
 
Here is the example code in CodingGround for you to experiment with.
 

Navigation: