Sub topic 5
Constant-Specific Behavior
Earlier chapters gave each enum constant its own data, such as the number of cents in a coin. Sometimes data is not enough, and each constant needs to do something different. A calculator has four operations: plus, minus, times, and divide. They all take two numbers and return one, but each one does different math.
This chapter shows how to give each enum constant its own version of a method. Java calls this a constant-specific class body. A constant-specific class body is a block of code in curly braces, written right after a constant, that holds methods for that one constant only.
The Problem: Behavior Kept Far From the Constant
Here is one way to write a calculator enum. It uses a switch inside a single method.
enum Operation {
PLUS, MINUS, TIMES, DIVIDE;
int apply(int a, int b) {
return switch (this) {
case PLUS -> a + b;
case MINUS -> a - b;
case TIMES -> a * b;
case DIVIDE -> a / b;
};
}
}This works. The switch expression is exhaustive, which means it covers every constant, so the compiler warns you if you add a constant and forget a case.
The switch does have a weakness, though. The math for PLUS is not next to PLUS. It sits in a separate method, mixed in with the code for every other constant. With four constants and one method, that is fine. With ten constants and five methods, you end up with five big switches, and you have to read all of them to understand one constant.
The Fix: An Abstract Method Plus One Body Per Constant
An abstract method is a method with a name and parameters but no body. It says "every version of this type must provide this method," and leaves the code to someone else. When you declare an abstract method in an enum, every constant must supply its own body for it.
enum Operation {
PLUS {
int apply(int a, int b) { return a + b; }
},
MINUS {
int apply(int a, int b) { return a - b; }
},
TIMES {
int apply(int a, int b) { return a * b; }
},
DIVIDE {
int apply(int a, int b) { return a / b; }
};
abstract int apply(int a, int b);
}Read it from the bottom up:
abstract int apply(int a, int b);promises that everyOperationhas anapplymethod.- Each constant is followed by
{ ... }. That block is its constant-specific class body. - Inside each body, the constant writes its own
apply.
Now the math for PLUS sits right next to the word PLUS. To see what one constant does, you read one small block.
A Complete Runnable Example
You can mix constant-specific bodies with the fields and constructors from the earlier chapter. Here each operation also stores the symbol used to print it.
enum Operation {
PLUS("+") {
int apply(int a, int b) { return a + b; }
},
MINUS("-") {
int apply(int a, int b) { return a - b; }
},
TIMES("*") {
int apply(int a, int b) { return a * b; }
},
DIVIDE("/") {
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);
}
public class Calculator {
public static void main(String[] args) {
for (Operation op : Operation.values()) {
System.out.println("6 " + op.symbol() + " 3 = " + op.apply(6, 3));
}
}
}Save it as Calculator.java, then compile and run it:
javac Calculator.java
java CalculatorThe output is:
6 + 3 = 9
6 - 3 = 3
6 * 3 = 18
6 / 3 = 2The argument in parentheses, like ("+"), comes first and goes to the constructor. The body in braces comes after it. The order is always: name, then arguments, then body.
The loop never asks which operation it has. It just calls op.apply(6, 3), and Java runs the right body. This is called dynamic dispatch: Java picks which version of a method to run based on the actual object at run time.
The Compiler Keeps You Honest
Suppose you add a new constant and forget its body:
enum Operation {
PLUS {
int apply(int a, int b) { return a + b; }
},
MODULO; // no body!
abstract int apply(int a, int b);
}This does not compile. MODULO has no apply, and the abstract method requires one. The compiler reports an error and points at the missing constant.
That is the main benefit of the abstract-method approach. You cannot add an operation and forget to say what it does. The safety lives in the enum itself, so you get it even if nobody ever writes a switch over Operation.
Overriding a Default Instead
You do not always need an abstract method. Sometimes most constants share the same behavior and only a few are different. In that case, write a normal method with a default body and override it only where needed. To override a method is to replace an inherited version with your own.
enum Shipping {
STANDARD,
EXPRESS {
@Override
int days() { return 1; }
},
FREIGHT {
@Override
int days() { return 10; }
};
int days() {
return 5;
}
}
public class ShippingDemo {
public static void main(String[] args) {
for (Shipping s : Shipping.values()) {
System.out.println(s + " takes " + s.days() + " days");
}
}
}Output:
STANDARD takes 5 days
EXPRESS takes 1 days
FREIGHT takes 10 daysSTANDARD has no body, so it uses the default of 5. EXPRESS and FREIGHT replace it. The @Override annotation is optional, but it is a good habit. If you misspell the method name, @Override makes the compiler complain instead of quietly creating a new, unused method.
Gotchas Worth Knowing
Extra methods in a body are invisible outside
A body can only usefully contain methods that the enum itself declares. If you add a brand-new method inside one constant's body, the rest of your code cannot call it.
enum Greeting {
HELLO {
void wave() { System.out.println("*waves*"); }
}
}
// Greeting.HELLO.wave(); // does not compile: Greeting has no wave()The type of Greeting.HELLO is Greeting, and Greeting has no wave method. If you want to call it, declare wave in the enum, either abstract or with a default.
Use the public method, not the private field
In the calculator, each body could need the symbol. Inside a body, call symbol() rather than reading the private field symbol directly. A body is a separate class, and it cannot see the enum's private fields by name. The compiler rejects the direct access, while the method call always works.
getClass() looks strange
Each constant with a body is really a small, unnamed class that extends the enum. That kind of class is called an anonymous subclass. You can see it if you print the class:
public class ClassDemo {
public static void main(String[] args) {
System.out.println(Shipping.STANDARD.getClass());
System.out.println(Shipping.EXPRESS.getClass());
System.out.println(Shipping.EXPRESS.getDeclaringClass());
}
}Run with the Shipping enum from above, this prints:
class Shipping
class Shipping$1
class ShippingEXPRESS reports a class named Shipping$1. If you need "which enum does this constant belong to," call getDeclaringClass(), which always returns the enum type. Everything else still works normally: ==, values(), valueOf(), switch, EnumSet, and EnumMap all treat EXPRESS as an ordinary Shipping constant.
Choosing an Approach
| Situation | Best tool |
|---|---|
| Constants differ only by a value, like cents or days | A field set through the constructor |
| Every constant needs its own logic | An abstract method with a body per constant |
| Most constants share logic, a few differ | A default method, overridden in a few bodies |
| The logic belongs to other code, not the enum | A switch expression in that other code |
The last row matters. If the behavior is about something outside the enum, such as how a user interface draws each operation, keep it out of the enum. Constant-specific bodies are best for behavior that is truly part of what the constant is.
Exercise
Add a POWER constant to the Operation enum from the runnable example. It should use the symbol "^" and return a raised to the power b, using integers only (assume b is zero or positive). What happens if you add POWER("^") with no body?
Show answer
Add this before the semicolon, putting a comma after DIVIDE's closing brace: POWER("^") { int apply(int a, int b) { int result = 1; for (int i = 0; i < b; i++) { result *= a; } return result; } }. With 6 and 3 it prints "6 ^ 3 = 216". If you write POWER("^") with no body, the program fails to compile, because apply is abstract and POWER does not provide it.
Exercise
An enum Size has constants SMALL, MEDIUM, LARGE, and HUGE. All of them cost 2 dollars extra except HUGE, which costs 5. Should you use an abstract method or a default method for extraCost()? Write the enum.
Show answer
A default method fits, because most constants share the same value: enum Size { SMALL, MEDIUM, LARGE, HUGE { @Override int extraCost() { return 5; } }; int extraCost() { return 2; } }. A constructor field like HUGE(5) would also work and is arguably simpler, since only the number changes and not the logic.
Exercise
Given the Shipping enum, what do Shipping.FREIGHT.getClass() == Shipping.class and Shipping.FREIGHT.getDeclaringClass() == Shipping.class evaluate to, and why?
Show answer
The first is false, because FREIGHT has a body, so its class is an anonymous subclass named Shipping$2. The second is true, because getDeclaringClass() always returns the enum type the constant belongs to.