Shall I enumerate the ways you drink me? Java enumerations

A narrow wooden tray has 2 coffees on it. The first is a small porcelain white cup on a saucer. The second is a small glass containing a latte.

An enumeration (enum) is a data type with a fixed list of related constants.

You might use an enumeration to describe the following:

Syntax

Java
enum CoffeeSize {
SMALL,
BIG,
HUGE,
OVERWHELMING;
}

We define an enumeration using the enum keyword, and make a list of the constant values.

We usually refer to a value by enum.value e.g. CoffeeSize.SMALL.

The semi-colon at the end of the constant list is optional.

Why should I use them?

When NOT to use enums?

If your list of constants is likely to change often. Adding a new constant requires the code to be updated, so this might become impractical for some applications. Instead you can use a variable, which sources its values from a database.

The facts

Constructors

I know, it seems weird having a constructor for a list of constants. Bear with me and I will explain! 🐻✌

Constructors for an enum type should be declared as private. The compiler allows constructors to be declared as public, but this can seem misleading, since new can never be used with enums!

Let’s get more specific about our sizes, and add a variable for the volume, measured in (fluid) ounces. We can call it ounces. We want to set the value of ounces for each size on creation. How do we do that? We will do this through the constructor.

Java
enum CoffeeSize {
SHORT(6),
BIG(8),
HUGE(10),
OVERWHELMING(16);

private int ounces;

//constructor
private CoffeeSize(int ounces) {
this.ounces = ounces;
}

public int getOunces(){
return ounces;
}
}

Rules

Final Words

An experienced developer friend of mine said to me recently, “When would you use enumerations?” in a withering, quizzical way! That surprised me. You won’t use them that often, but they can add value to your code.

Let me know if you are interested in any Java topics, and maybe I will write about them.

Happy hacking! 👩‍💻👨‍💻🙌

Tagged