Sub topic 6
Enums That Implement Interfaces
You have already given enum constants fields, constructors, and methods. Now you will make an enum work in code that was written for other types too. You do this by having the enum implement an interface.
An interface is a list of methods that a type promises to provide. Any class can implement an interface, and so can an enum. An enum cannot extend another class, because every enum already extends java.lang.Enum behind the scenes. It can still implement as many interfaces as you like.
Why This Matters
Suppose a café sells drinks and snacks. The drink menu is fixed, so an enum fits it well. Snacks change every day, so a regular class fits them better. The checkout code only needs a price for each item, so it should not have to care which kind of item it gets.
An interface gives both types the same "shape". The checkout code then works with the interface and accepts either one.
A Worked Example
Save this as Main.java and run it with java Main.java.
import java.util.List;
interface Priced {
int priceInCents();
}
enum Drink implements Priced {
COFFEE(250), TEA(200), JUICE(300);
private final int cents;
Drink(int cents) {
this.cents = cents;
}
@Override
public int priceInCents() {
return cents;
}
}
class Snack implements Priced {
private final String name;
private final int cents;
Snack(String name, int cents) {
this.name = name;
this.cents = cents;
}
@Override
public int priceInCents() {
return cents;
}
@Override
public String toString() {
return name;
}
}
public class Main {
static int total(List<Priced> items) {
int sum = 0;
for (Priced item : items) {
sum += item.priceInCents();
}
return sum;
}
public static void main(String[] args) {
List<Priced> order = List.of(Drink.COFFEE, new Snack("Cookie", 150), Drink.TEA);
System.out.println(order); // [COFFEE, Cookie, TEA]
System.out.println(total(order)); // 600
}
}Here is what happens:
Drink implements Pricedpromises that everyDrinkconstant has apriceInCents()method.- The enum keeps its price in a
finalfield, as you saw in the earlier chapter. Snackkeeps the same promise in its own way.totalonly knows aboutPriced, so it adds up drinks and snacks the same way.
Each Constant Can Implement It Differently
In the chapter on constant-specific behavior, each constant had its own body for an abstract method. An interface method works the same way. When the enum itself does not implement the method, each constant must implement it:
interface Greeter {
String greet(String name);
}
enum Language implements Greeter {
ENGLISH {
public String greet(String name) { return "Hello, " + name; }
},
SPANISH {
public String greet(String name) { return "Hola, " + name; }
};
}
// Language.SPANISH.greet("Ana") returns "Hola, Ana"The "Extensible Enum" Trick
You cannot add new constants to an enum from outside its file. An interface gets around this. If your code accepts Greeter instead of Language, someone else can write a new enum or class that implements Greeter, and your code will accept it without any changes.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| `enum Drink extends Item` | Compile error: enums cannot extend classes | Make `Item` an interface and use `implements` |
| Forgetting `public` on the method | Compile error about weaker access | Add `public` |
| Neither the enum nor every constant implements the method | Compile error: the enum is missing the method | Implement it once in the enum or in every constant |
Exercise
Add a constant WATER that costs 100 cents to the Drink enum. Then build an order of WATER and a Snack named "Muffin" that costs 275 cents. What does total(order) print?
Show answer
Add WATER(100) to the constant list, for example COFFEE(250), TEA(200), JUICE(300), WATER(100);. With List<Priced> order = List.of(Drink.WATER, new Snack("Muffin", 275));, total(order) returns 100 + 275, so it prints 375.
Exercise
Why can an enum implement an interface but not extend a class?
Show answer
Every enum already extends java.lang.Enum, and a Java type can extend only one class. A type can implement any number of interfaces, so enums can implement interfaces freely.