Java Item 34: Use enums instead of int constants

Posted on Sat 23 July 2022 in Java

Introduction

An enumerated type is a type whole legal values consist of a fixed set of constants, such as the seasons of the year, the planets in the solar system, or the suits in a deck of playing cards.

Here is how an enumerated type looks in C:

enum Operation { PLUS, MINUS, DIVIDE, MULTIPLY };

and Java:

public enum Operation { PLUS, MINUS, DIVIDE, MULTIPLY };

Despite its similarity, enum types in Java are used as classes. That is, an enun type have instances with data (state) and methods (behavior).

[Enum types] are classes that export one instance for each enumeration constant via public static field field.

There are four instances in our Operation enum.

In fact, it is simlar to the enum types in other programmin languages.

Sidenotes

// WeightTable.java
for (Planet p : Planet.values()) { ... } 

Here, we need to specify the name of the enum and the name of the method.

// PayrollDay.java
for (PayrollDay day : values()) { ... }

The second example is valid because the main function takes place inside the enum PayrollDay. As a result, the values() function can be invoked without refering to the name of the enum, PayrollDay.