Enums with behaviour and interfaces
40 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Enum constants can carry their own behaviour, not just data: PLUS adds, MINUS subtracts, and a credit card charges a fee while UPI does not. Each constant keeps its own version of a method.
A method body for each constant
A constant-specific body is a block in braces after an enum constant that overrides a method for that constant only. Java turns it into an anonymous subclass of the enum, so each constant can behave differently.
A calculator needs PLUS to add and MINUS to subtract. Declare an abstract method in the enum, and give each constant its own version of it in braces.
Example 1 · A calculator: one abstract method, four bodies
enum Operation { PLUS("+") { @Override int apply(int a, int b) { return a + b; } }, MINUS("-") { @Override int apply(int a, int b) { return a - b; } }, TIMES("*") { @Override int apply(int a, int b) { return a * b; } }, DIVIDE("/") { @Override int apply(int a, int b) { return a / b; } };
private final String symbol;
Operation(String symbol) { this.symbol = symbol; }
String getSymbol() { return symbol; }
abstract int apply(int a, int b);}
public class CalculatorDemo { public static void main(String[] args) { int a = 12; int b = 4; for (Operation op : Operation.values()) { System.out.println(a + " " + op.getSymbol() + " " + b + " = " + op.apply(a, b)); } }}12 + 4 = 16 12 - 4 = 8 12 * 4 = 48 12 / 4 = 3
What this code does
abstract int apply(...)says every constant must haveapply. Each constant's braces hold its own version, after its constructor arguments.- The loop calls the same
op.apply(a, b)four times, and dispatch runs a different body each time.
Each body works like the anonymous classes from Functional interfaces (opens in a new tab): a small unnamed class that extends the enum and overrides the method. op.apply(a, b) then uses dynamic method dispatch (opens in a new tab), so the constant's own version runs.
@Override on each constant's method, as with any override. It catches a misspelt method name.Abstract method or default body?
A shop charges a fee only for card and cash payments. A normal method body in the enum can be the default, and only the constants that differ override it.
Example 2 · A default body that some constants override
enum PaymentMode { UPI, DEBIT_CARD, CREDIT_CARD { @Override int fee(int amount) { return amount * 2 / 100; } }, CASH_ON_DELIVERY { @Override int fee(int amount) { return 40; } };
int fee(int amount) { return 0; }}
public class CheckoutDemo { public static void main(String[] args) { int cart = 2400; for (PaymentMode m : PaymentMode.values()) { int fee = m.fee(cart); System.out.println(m + ": Rs. " + cart + " + Rs. " + fee + " = Rs. " + (cart + fee)); } }}UPI: Rs. 2400 + Rs. 0 = Rs. 2400 DEBIT_CARD: Rs. 2400 + Rs. 0 = Rs. 2400 CREDIT_CARD: Rs. 2400 + Rs. 48 = Rs. 2448 CASH_ON_DELIVERY: Rs. 2400 + Rs. 40 = Rs. 2440
What this code does
feehas a normal body in the enum.UPIandDEBIT_CARDhave no braces, so they use it; the other two override it.- This is shorter, but a new constant such as
WALLETwould silently be free. Example 3 shows how anabstractmethod prevents that.
Example 3 · Mistake: a new constant without its body
enum Operation { PLUS { @Override int apply(int a, int b) { return a + b; } }, MODULO;
abstract int apply(int a, int b);}
public class ForgotBodyDemo { public static void main(String[] args) { System.out.println(Operation.PLUS.apply(7, 3)); }}ForgotBodyDemo.java:8: error: Operation is abstract; cannot be instantiated
MODULO;
^
1 errorWhat this code does
MODULOhas no braces, so Java would have to create a plainOperationobject. But the enum has an abstract method, so it cannot.- Fix: give
MODULOits body,{ @Override int apply(int a, int b) { return a % b; } }. The compiler will not let any constant skip it.
With an abstract method, every constant must have a body, so nobody can add a constant without its behaviour. A default body is shorter, but a new constant quietly inherits it. A switch expression without default (opens in a new tab) is just as safe as an abstract method: keep behaviour inside the constants when it belongs to them, and use a switch when only one place needs the decision.
Enums can implement interfaces
An enum can implement one or more interfaces with implements, just like a class. Each constant is then also an object of the interface type, usable wherever that interface is expected.
A canteen bill holds snacks from a fixed menu and custom cakes. Both can go into one list if the snack enum and the cake class implement the same Priced interface.
Example 4 · An enum that implements an interface
interface Priced { int price();
String label();}
enum Snack implements Priced { SAMOSA(15), VADA_PAV(20), CHAI(10);
private final int price;
Snack(int price) { this.price = price; }
@Override public int price() { return price; }
@Override public String label() { return name(); }}
class Cake implements Priced { private String flavour; private int kg;
Cake(String flavour, int kg) { this.flavour = flavour; this.kg = kg; }
@Override public int price() { return kg * 600; }
@Override public String label() { return flavour + " cake (" + kg + " kg)"; }}
public class CanteenBillDemo { public static void main(String[] args) { Priced[] order = { Snack.SAMOSA, Snack.SAMOSA, Snack.CHAI, new Cake("Chocolate", 1) }; int total = 0; for (Priced item : order) { System.out.println(item.label() + ": Rs. " + item.price()); total = total + item.price(); } System.out.println("Total: Rs. " + total); }}SAMOSA: Rs. 15 SAMOSA: Rs. 15 CHAI: Rs. 10 Chocolate cake (1 kg): Rs. 600 Total: Rs. 640
What this code does
Snack implements Priced, so every snack constant is also aPriced. Interface methods arepublic, in an enum too.- The array mixes enum constants with a normal
Cakeobject. The loop does not care which is which.
The interface methods can be written once in the enum, as here, or separately inside each constant body. Shared helpers can live in the interface as default methods (opens in a new tab).
No extends, in either direction
java.lang.Enum is the class that every enum automatically extends. Because a Java class can have only one parent, an enum cannot extend any other class; it can only implement interfaces.
A developer wants Snack to reuse an Item class with extends. As in one parent only (opens in a new tab), the single parent slot is already taken by java.lang.Enum.
Example 5 · Mistake: an enum cannot extend a class
class Item { int price;}
enum Snack extends Item { SAMOSA, CHAI}
public class ExtendsDemo { public static void main(String[] args) { System.out.println(Snack.CHAI); }}ExtendsDemo.java:5: error: '{' expected
enum Snack extends Item {
^
ExtendsDemo.java:5: error: enum constant expected here
enum Snack extends Item {
^
ExtendsDemo.java:6: error: <identifier> expected
SAMOSA, CHAI
^
ExtendsDemo.java:6: error: ';' expected
SAMOSA, CHAI
^
ExtendsDemo.java:7: error: ',', '}', or ';' expected
}
^
ExtendsDemo.java:13: error: reached end of file while parsing
}
^
6 errorsWhat this code does
- An enum already extends
java.lang.Enum, so javac does not acceptextendsafter an enum name. Only the first error,'{' expected, matters; the rest follow from it. - Fix: remove
extends Item. To share methods with other types, useimplementswith an interface.
It works the other way too: no class can extend an enum. An enum without constant bodies is implicitly final, so class VipLevel extends Level gives cannot inherit from final Level and enum classes are not extensible. With constant bodies, only those bodies extend it.
Fix the error
Fix the enum behaviour
Read the error, then pick the line that fixes it.
Round 1 of 4
Every operation must define apply().
Error
Operation.java:6: error: Operation is abstract; cannot be instantiated
State machines with enums
A state machine is a model in which something is always in one of a fixed set of states and may move only along allowed paths, such as an order going from PLACED to PACKED to SHIPPED.
An order can be cancelled only before it ships. Make each state a constant, and let methods on the enum, such as next() and canCancel(), describe the allowed moves.
Example 6 · Order status as a state machine
enum OrderStatus { PLACED, PACKED, SHIPPED, DELIVERED, CANCELLED;
OrderStatus next() { return switch (this) { case PLACED -> PACKED; case PACKED -> SHIPPED; case SHIPPED, DELIVERED -> DELIVERED; case CANCELLED -> CANCELLED; }; }
boolean canCancel() { return this == PLACED || this == PACKED; }}
class Order { private final int id; private OrderStatus status = OrderStatus.PLACED;
Order(int id) { this.id = id; }
void advance() { OrderStatus old = status; status = status.next(); if (old == status) { System.out.println("Order " + id + ": already " + status); } else { System.out.println("Order " + id + ": " + old + " -> " + status); } }
void cancel() { if (status.canCancel()) { status = OrderStatus.CANCELLED; System.out.println("Order " + id + ": cancelled"); } else { System.out.println("Order " + id + ": cannot cancel, already " + status); } }}
public class OrderFlowDemo { public static void main(String[] args) { Order a = new Order(501); a.advance(); a.advance(); a.cancel(); a.advance(); a.advance();
Order b = new Order(502); b.advance(); b.cancel(); b.advance(); }}Order 501: PLACED -> PACKED Order 501: PACKED -> SHIPPED Order 501: cannot cancel, already SHIPPED Order 501: SHIPPED -> DELIVERED Order 501: already DELIVERED Order 502: PLACED -> PACKED Order 502: cancelled Order 502: already CANCELLED
What this code does
- The rules live in the enum:
next()says where each state goes, andcanCancel()says when cancelling is allowed. Inside the enum,switch (this)switches on the current constant. Orderonly asks its status. Order 501 cannot be cancelled after shipping, and a cancelled order never moves again.
Inside the enum, switch (this) switches on the constant the method was called on. The Order class only asks its status what is allowed, instead of repeating if checks everywhere.
Next step
Check your understanding
12 quick questions