# A constant is an object, so it can carry its own value

The vending machine takes four coins. Read `enum Coin { NICKEL, DIME, QUARTER, DOLLAR }` as four
named integers and the value has to live somewhere else, so you write the table:

```java
private static final Map<Coin, Integer> MINOR_VALUE = Map.of(
        Coin.NICKEL, 5, Coin.DIME, 10, Coin.QUARTER, 25);
```

That was right the day it was written, when the machine took three denominations. It takes four now.
Nothing stopped compiling when `DOLLAR` was declared, because a map has no opinion about which keys
it ought to hold. You find out at the till:

```
java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because the
return value of "java.util.Map.get(Object)" is null
```

So put the number where it cannot drift. A Java enum is a class with a fixed set of instances, and
an instance can hold a `final` field:

```java
NICKEL(5), DIME(10), QUARTER(25), DOLLAR(100);

private final int minorValue;

Coin(int minorValue) { this.minorValue = minorValue; }
```

`QUARTER.minorValue()` returns 25 because `QUARTER` is an object that was constructed with 25. The
constructor runs once per constant, and it is private whether you write a modifier or not. Those
four are the only `Coin` instances that will ever exist.

The stale table is now unwritable. A fifth denomination cannot be declared without a value, because
the constructor demands one, and `javac` asks at the declaration rather than letting a map answer
`null` in production.

Constants can carry methods too, one body each. That is the part with no C++ equivalent, and
`worked/NOTES.md` gives the threshold for reaching for it.
