News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

Java Tutorial – 20 – Enum

An enumeration is a type that consists of a fixed list of named constants. To create one, the enum keyword is used followed by a name and a code block, containing a comma separated list of constant elements. The access level for an enumeration is the same as for a class. Package-private by default, but it can also be set to public if it is declared in a file of the same name. Just as with classes, an enumeration can be contained within a class, where it can then be set to any access level.

enum Speed
{
  STOP, SLOW, NORMAL, FAST
}

An object of the enum type above can hold any one of the four defined constants. The enum constants are accessed as if they were static fields of a class.

Speed s = Speed.SLOW;

Enum example

The switch statement provides a good example of when an enumeration can be useful. Compared to using ordinary constants, an enumeration has the advantage of allowing the programmer to clearly specify what constant values are allowed. This provides compile-time type safety. Note that when using an enum in a switch statement, the case labels are not qualified with the name of the enum.

switch(s) { case SLOW: break; }

Enum class

In Java, the enum type is more powerful than its counterparts in other languages, such as C++ or C#. It is essentially a special kind of class, and can include anything that a class can include. To add a class member the list of constants must be terminated with a semicolon, and the member must be declared after the constants. In the example below, an integer is added to the enum, which will hold the actual speed that the elements represent.

enum Speed
{
  STOP, SLOW, NORMAL, FAST;
  public int speed;
}

To set this field, a constructor needs to be added as well. A constructor in an enumeration must have either private or package-private access and is not called in the same way as for a regular class. Instead, the parameters to the constructor are given after the constant elements, as seen below. For example, if a Speed enum object is assigned the constant SLOW, then the argument 5 will be passed to the constructor for that enum instance.

enum Speed
{
  STOP(0), SLOW(5), NORMAL(10), FAST(20);
  public int speed;
 
  Speed(int s) { speed = s; }
}

Another difference that enum types have when compared to regular classes, is that they implicitly extend from the java.lang.Enum class. In addition to the members inherited from this class, the compiler will also automatically add two static methods to the enumeration, namely values and valueof. The values method returns an array of the constant elements declared in the enum, and valueof returns the enum constant of the specified enum name.

Speed[] a = Speed.values();
Speed s = Speed.valueOf(a[0].toString()); // Speed.STOP
Recommended additional reading:
Sams - Teach Yourself Java in 24 Hours