Sub topic 3
Giving Enum Constants Data and Behavior
So far, each enum constant has been just a name. MONDAY is MONDAY, and that is all it knows. Real programs often need more. A coin has a value in cents. A planet has a mass. A traffic light color has a wait time.
In this chapter you will learn to attach data and behavior to each constant. You will add fields, which are variables that belong to an object. You will add a constructor, which is the special code that runs when an object is created. You will also add methods, which are named blocks of code you can call.
By the end, your enums will work like small classes with a fixed list of objects.
Why Attach Data to Constants?
Imagine you need the value of each coin. Without data inside the enum, you might write a separate method like this:
enum Coin { PENNY, NICKEL, DIME, QUARTER }
public class Main {
static int centsOf(Coin coin) {
return switch (coin) {
case PENNY -> 1;
case NICKEL -> 5;
case DIME -> 10;
case QUARTER -> 25;
};
}
public static void main(String[] args) {
System.out.println(centsOf(Coin.DIME)); // 10
}
}This works, but the value of a dime now lives far away from the DIME constant. If someone adds a HALF_DOLLAR constant, they must remember to update centsOf too. That is easy to forget when the code is spread across many files.
A better plan is to store the value right inside each constant. Then the data and the name always travel together.
Adding a Field and a Constructor
Here is the Coin enum with its own data:
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int cents;
Coin(int cents) {
this.cents = cents;
}
public int cents() {
return cents;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Coin.DIME.cents()); // 10
System.out.println(Coin.QUARTER.cents()); // 25
}
}Let's walk through each part.
PENNY(1)lists a constant and passes the number1to the constructor. Each constant gets its own number in parentheses.- The semicolon after
QUARTER(25)ends the list of constants. You need it whenever more code follows the list. private final int cents;declares a field.privatemeans only code inside the enum can touch it directly.finalmeans its value cannot change after it is set.Coin(int cents) { ... }is the constructor. It copies the number it receives into the field.public int cents()is an accessor, a method whose only job is to return a field's value.
How the Constants Get Built
You never write new Coin(10) yourself. Java does it for you. When the program first uses the Coin enum, Java creates each constant once by calling the constructor with the values you wrote in parentheses. After that, the same four objects are reused for the rest of the program.
Because each constant is built only once, Coin.DIME always points to the same object. That is why comparing constants with == is safe.
The Constructor Is Always Private
An enum constructor is private, which means code outside the enum cannot call it. This is true even if you leave out the word private. Java adds it for you.
This rule keeps the set of constants fixed. Nobody can make a fifth coin from outside the enum. Writing public or protected on an enum constructor is a compile error:
enum Coin {
PENNY(1);
private final int cents;
public Coin(int cents) { // error: modifier public not allowed here
this.cents = cents;
}
}| Constructor modifier | Allowed in an enum? |
|---|---|
| none (just `Coin(int cents)`) | Yes, treated as private |
| `private` | Yes |
| `public` | No, compile error |
| `protected` | No, compile error |
Storing More Than One Value
A constant can carry several values. You just add more fields and more constructor parameters. Here is a planet enum with mass and radius:
enum Planet {
MERCURY(3.303e23, 2.4397e6),
EARTH(5.976e24, 6.37814e6),
JUPITER(1.9e27, 7.1492e7);
private static final double G = 6.67300e-11;
private final double mass; // in kilograms
private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
return G * mass / (radius * radius);
}
public double weightOf(double earthWeight) {
double earthGravity = EARTH.surfaceGravity();
return earthWeight * surfaceGravity() / earthGravity;
}
}
public class Main {
public static void main(String[] args) {
double myWeight = 70.0;
for (Planet p : Planet.values()) {
System.out.printf("%s: %.1f%n", p, p.weightOf(myWeight));
}
}
}The output looks like this:
MERCURY: 26.4
EARTH: 70.0
JUPITER: 177.1Notice two kinds of methods here. mass() and radius() just return stored data. surfaceGravity() and weightOf() compute new answers from that data. Both kinds are normal in an enum.
Looking Up a Constant by Its Data
The built-in valueOf("DIME") finds a constant by its name. Sometimes you need to find one by its data instead. For example, which coin is worth 10 cents?
You can write a static method, which is a method that belongs to the enum itself rather than to one constant:
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int cents;
Coin(int cents) {
this.cents = cents;
}
public int cents() {
return cents;
}
public static Coin fromCents(int cents) {
for (Coin coin : values()) {
if (coin.cents == cents) {
return coin;
}
}
throw new IllegalArgumentException("No coin worth " + cents + " cents");
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Coin.fromCents(10)); // DIME
System.out.println(Coin.fromCents(3)); // throws IllegalArgumentException
}
}The loop checks each constant in turn. If none match, the method throws an exception so the mistake is loud and clear. Returning null would be quieter, and the error could then show up much later, somewhere harder to trace.
Use Fields Instead of ordinal()
You met ordinal() earlier. It returns a constant's position in the list: PENNY is 0, NICKEL is 1, and so on. It is tempting to use that position as data. Don't.
// Fragile: depends on the order of the constants
int badCents = new int[] {1, 5, 10, 25}[coin.ordinal()];
// Safe: the value is stored with the constant
int goodCents = coin.cents();If someone reorders the constants or adds a new one in the middle, every ordinal after it shifts. The fragile version then returns wrong values with no error. A field stays correct no matter where the constant sits in the list.
Common Mistakes and Edge Cases
Forgetting the semicolon
If the enum has fields or methods, the constant list must end with ;. Leaving it out gives a confusing compile error on the next line.
Making fields changeable
Java lets you write a non-final field and a setter method in an enum. Avoid this. Every part of the program shares the same Coin.DIME object. If one piece of code changed the dime's value to 12, every other piece of code would suddenly see 12 too. Keep enum fields final.
Reading static fields in the constructor
The constants are created before most static fields in the enum get their values. So a constructor that reads a static field may see an empty value, and Java often refuses to compile such code at all. In the Planet example, G is used in surfaceGravity(), not in the constructor, so it is safe. A static final constant set to a plain number or string, like G, is fine to read anywhere. But keep constructors simple: just store the values you are given.
A constructor with no arguments
If a constant has no parentheses, Java calls a constructor with no parameters. Then you must provide one:
enum Size {
SMALL(1), MEDIUM, LARGE(3);
private final int level;
Size() {
this.level = 2; // used by MEDIUM
}
Size(int level) {
this.level = level;
}
public int level() {
return level;
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Size.MEDIUM.level()); // 2
}
}An enum can have more than one constructor, just like a class. Each constant picks the one that matches its arguments.
Overriding toString()
By default, printing a constant shows its name, like QUARTER. You can override toString(), which means you write your own version that replaces the default one:
enum Coin {
PENNY(1), NICKEL(5), DIME(10), QUARTER(25);
private final int cents;
Coin(int cents) {
this.cents = cents;
}
@Override
public String toString() {
return name().toLowerCase() + " (" + cents + "¢)";
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Coin.QUARTER); // quarter (25¢)
}
}name() still returns "QUARTER", and valueOf("QUARTER") still works. Only the printed text changes. Never change name() itself. You can't, because Java marks it final.
Summary
| Feature | What it does |
|---|---|
| `PENNY(1)` | Passes data to the constructor for that constant |
| `private final` field | Stores data that never changes |
| Constructor | Runs once per constant; always private |
| Accessor method | Returns a stored value |
| Computed method | Builds an answer from stored values |
| Static lookup method | Finds a constant by its data |
| `toString()` override | Changes how a constant prints |
Exercise
Write an enum TrafficLight with constants RED, YELLOW, and GREEN. Each one should store how many seconds it lasts: RED 30, YELLOW 5, GREEN 25. Add a method seconds() that returns that number.
Show answer
enum TrafficLight { RED(30), YELLOW(5), GREEN(25); private final int seconds; TrafficLight(int seconds) { this.seconds = seconds; } public int seconds() { return seconds; } } — The constants come first and end with a semicolon. The final field holds the time, the constructor sets it, and the accessor returns it.
Exercise
A teammate writes public Coin(int cents) inside the Coin enum. What happens, and why does Java have this rule?
Show answer
The code does not compile, because enum constructors cannot be public or protected. The rule stops outside code from creating new constants, so the set of coins stays fixed.
Exercise
Why is coin.cents() safer than looking up a value with coin.ordinal() in an array?
Show answer
The ordinal is the constant's position in the list. It changes if constants are reordered or a new one is inserted, and the array lookup would then silently return wrong values. A field is stored with its constant, so it stays correct.
Exercise
Add a static method longest() to TrafficLight that returns the constant with the most seconds.
Show answer
public static TrafficLight longest() { TrafficLight best = RED; for (TrafficLight t : values()) { if (t.seconds > best.seconds) { best = t; } } return best; } — It starts with any constant, loops over values(), and keeps the one with the largest seconds. For the given data it returns RED.