Enums with behaviour

Lesson 044 introduced the enum as a list of named constants. The constants are objects of a class the compiler writes, so an enum may also hold fields, run a constructor, and give each constant its own behaviour. That turns a list of names into a small closed hierarchy, and it is where an enum beats a group of static final int constants.

A method per constant

An enum may declare an abstract method, and then every constant supplies the body in its own brace pair. Each constant becomes a small anonymous subclass, and the call dispatches to the one that matches:

public class OperationDemo { public static void main(String[] args) { for (Operation op : Operation.values()) { System.out.println(op.symbol() + " " + op.apply(7, 2)); } System.out.println(Operation.valueOf("ADD").apply(1, 2)); System.out.println(Operation.ADD.ordinal() + " " + Operation.ADD.name()); } } enum Operation { ADD("+") { @Override int apply(int a, int b) { return a + b; } }, SUBTRACT("-") { @Override int apply(int a, int b) { return a - b; } }, MULTIPLY("*") { @Override int apply(int a, int b) { return a * b; } }; private final String symbol; Operation(String symbol) { this.symbol = symbol; } String symbol() { return symbol; } abstract int apply(int a, int b); }

javac -Xlint:all OperationDemo.java
java OperationDemo

+ 9
- 5
* 14
3
0 ADD

The switch over the operation would also work, and the abstract method is better here: a new constant cannot be added without its body, so the compiler refuses an incomplete enum. Ordinal 0 is ADD because it is declared first, and the order of the declaration is the order of values().

A field per constant

A constant may carry values of its own, passed to a constructor that runs once per constant. The planets below hold a mass and a radius, and their methods use the two:

public class PlanetDemo { public static void main(String[] args) { for (Planet planet : Planet.values()) { System.out.printf("%-8s %5.2f %6.1f%n", planet, planet.surfaceGravity(), planet.escapeVelocity()); } System.out.println(Planet.MARS.compareTo(Planet.EARTH)); } } enum Planet { MERCURY(3.303e+23, 2.4397e6), EARTH(5.976e+24, 6.37814e6), MARS(6.421e+23, 3.3972e6); private static final double G = 6.67430e-11; private final double mass; private final double radius; Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } double surfaceGravity() { return G * mass / (radius * radius); } double escapeVelocity() { return Math.sqrt(2 * surfaceGravity() * radius); } }

javac -Xlint:all PlanetDemo.java
java PlanetDemo

MERCURY 3.70 4251.1
EARTH 9.80 11183.5
MARS 3.71 5022.9
1

The constructor of an enum is private whatever the source says, because a constant is the only instance that may exist. The last line is compareTo, which an enum gets from java.lang.Enum and which compares the ordinals: MARS comes after EARTH in the declaration, so the answer is 1.

values, valueOf, ordinal and name

Four members come with every enum. values() returns a fresh array of the constants in declaration order. valueOf("NAME") returns the constant with that exact name and throws IllegalArgumentException for a name it does not know. name() returns the declared name as a string, and ordinal() its zero-based position.

A name that is not there is the one call that fails at run time, so a program that reads an enum from a file or a command line calls valueOf inside a try, or compares against values() first. Lesson 096 reads the exception in full.

EnumSet and EnumMap

An enum has a fixed set of members, and the JDK has two collections that exploit it. EnumSet is a bit set: a set of the constants of one enum, in declaration order, in one long when the enum is small. EnumMap is an array indexed by the ordinal, so a lookup is an array access:

import java.util.EnumMap; import java.util.EnumSet; import java.util.Map; public class SetsDemo { enum Day { MON, TUE, WED, THU, FRI, SAT, SUN } public static void main(String[] args) { EnumSet<Day> weekend = EnumSet.of(Day.SAT, Day.SUN); EnumSet<Day> work = EnumSet.range(Day.MON, Day.FRI); System.out.println(weekend); System.out.println(work); System.out.println(EnumSet.complementOf(weekend)); Map<Day, Integer> hours = new EnumMap<>(Day.class); hours.put(Day.MON, 8); hours.put(Day.SAT, 0); System.out.println(hours); System.out.println(hours.getOrDefault(Day.SUN, 4)); } }

javac -Xlint:all SetsDemo.java
java SetsDemo

[SAT, SUN]
[MON, TUE, WED, THU, FRI]
[MON, TUE, WED, THU, FRI]
{MON=8, SAT=0}
4

Both print in declaration order and not in insertion order, which no HashSet or HashMap promises. The last line is the getOrDefault of lesson 072: Sunday was never put in, and four is the answer the caller chose.

An enum in a switch

A switch over an enum needs no default when every constant has a case, and with arrow labels the cases are one line each:

public class SwitchDemo { public static void main(String[] args) { for (Color color : Color.values()) { System.out.println(color + ": " + kind(color)); } } static String kind(Color color) { return switch (color) { case RED, GREEN, BLUE -> "primary"; }; } } enum Color { RED, GREEN, BLUE }

javac -Xlint:all SwitchDemo.java
java SwitchDemo

RED: primary
GREEN: primary
BLUE: primary

The switch is exhaustive because the three constants are all of Color. Add a fourth constant and this program stops compiling, which is the point: the compiler lists the places that must learn about the new value. A default would have hidden that list.

Exercises

  1. Add DIVIDE to Operation and check that the build fails until its body is written.
  2. Give Planet a method that returns the planet with the largest surface gravity.
  3. Put a name into valueOf that is not a constant, catch the exception and print its message.
  4. Replace the EnumMap of working hours with an EnumSet of short days and compare the two outputs.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What may an enum constant have in its own braces?

    Answer

    A body for the abstract methods the enum declares

    Each constant with a body is an anonymous subclass that implements the abstract methods.

  2. What is the constructor of an enum?

    Answer

    Private, because the constants are its only instances

    An enum cannot be instantiated from outside, so the constructor is private whatever the source says.

  3. What does values() return?

    Answer

    A fresh array of the constants in declaration order

    The array is a copy, and its order is the order the constants are declared in.

  4. What does this program print? public class Q1 { public static void main(String[] args) { System.out.println(E.B.ordinal()); System.out.println(E.B.name()); } } enum E { A, B, C }

    Answer

    1 then B

    The ordinal counts from zero, so the second constant is 1.

  5. What does this program print? public class Q2 { public static void main(String[] args) { for (E e : E.values()) { System.out.print(e + " "); } } } enum E { X, Y }

    Answer

    X Y

    values() follows the declaration order and toString is the constant name.

  6. What does this program print? public class Q3 { public static void main(String[] args) { E e = E.valueOf("B"); System.out.println(e == E.B); } } enum E { A, B }

    Answer

    true

    There is one instance of each constant, so the reference comparison is true.

  7. What does this program print? public class Q4 { public static void main(String[] args) { System.out.println(kind(E.B)); } static String kind(E e) { return switch (e) { case A -> "a"; case B -> "b"; }; } } enum E { A, B }

    Answer

    b

    The switch selects the case of the constant and returns its text.

  8. What does this program print? public class Q5 { public static void main(String[] args) { for (P p : P.values()) { System.out.print(p.price() + " "); } } } enum P { SMALL(10), LARGE(20); private final int price; P(int price) { this.price = price; } int price() { return price; } }

    Answer

    10 20

    The constructor runs once per constant with the value each one names.

  9. Why does an EnumSet print in declaration order?

    Answer

    It is a bit set over the constants, whose order is the declaration order

    The bits are stored in ordinal order, so iteration follows the declaration.

  10. What happens when valueOf gets a name no constant has?

    Answer

    It throws IllegalArgumentException at run time

    The name is looked up at run time, so the mistake appears then, not at compile time.

The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.

Article author: Arthur Isaev