Enums: Type-Safe Constants

Introduction

An enum defines a fixed set of named constants—days of week, order status, difficulty level. Enums are classes in Java: they can have fields, constructors, and methods, and they work well with switch.

Prerequisites

Why Not Use Strings or int Codes?

java
String status = "SHIPPED";  // typo "SHIPED" only fails at runtime
int statusCode = 2;         // magic numbers — unclear meaning

Enums give compile-time checks and IDE autocomplete:

java
OrderStatus status = OrderStatus.SHIPPED;

1) Basic Enum

java
public enum Day {
    MONDAY,
    TUESDAY,
    WEDNESDAY,
    THURSDAY,
    FRIDAY,
    SATURDAY,
    SUNDAY
}
java
Day today = Day.MONDAY;
System.out.println(today);           // MONDAY
System.out.println(today.name());    // "MONDAY"
System.out.println(today.ordinal()); // 0 (position — avoid relying on it)

2) Enum with Fields and Constructor

Enums can carry data. Constructors are private (only enum constants call them):

java
public enum Difficulty {
    EASY(1, "Casual"),
    NORMAL(2, "Standard"),
    HARD(3, "Expert");
 
    private final int level;
    private final String label;
 
    Difficulty(int level, String label) {
        this.level = level;
        this.label = label;
    }
 
    public int getLevel() {
        return level;
    }
 
    public String getLabel() {
        return label;
    }
}
java
Difficulty d = Difficulty.HARD;
System.out.println(d.getLabel());  // Expert

3) Enum Methods

Add behavior per constant:

java
public enum Operation {
    PLUS {
        @Override
        double apply(double a, double b) {
            return a + b;
        }
    },
    MINUS {
        @Override
        double apply(double a, double b) {
            return a - b;
        }
    };
 
    abstract double apply(double a, double b);
}

Constant-specific bodies are advanced but common in frameworks.

4) switch with Enums

Modern switch is clean and type-safe:

java
Day day = Day.SATURDAY;
 
String type = switch (day) {
    case SATURDAY, SUNDAY -> "Weekend";
    default -> "Weekday";
};
System.out.println(type);

Classic style still works:

java
switch (day) {
    case SATURDAY:
    case SUNDAY:
        System.out.println("Weekend");
        break;
    default:
        System.out.println("Weekday");
        break;
}

5) values() and valueOf

java
for (Day d : Day.values()) {
    System.out.println(d);
}
 
Day parsed = Day.valueOf("FRIDAY");

valueOf throws if the name is invalid—validate user input before calling.

6) Enums Implementing Interfaces

Enums can implement interfaces like any class (Interfaces):

java
public interface Describable {
    String describe();
}
 
public enum Season implements Describable {
    SPRING("Warm start"),
    SUMMER("Hot"),
    AUTUMN("Cool"),
    WINTER("Cold");
 
    private final String description;
 
    Season(String description) {
        this.description = description;
    }
 
    @Override
    public String describe() {
        return description;
    }
}

Real Mini Example: Order Status

java
public class OrderService {
 
    public enum OrderStatus {
        NEW, PAID, SHIPPED, DELIVERED, CANCELLED
    }
 
    static String messageFor(OrderStatus status) {
        return switch (status) {
            case NEW -> "Waiting for payment";
            case PAID -> "Preparing shipment";
            case SHIPPED -> "On the way";
            case DELIVERED -> "Completed";
            case CANCELLED -> "Order cancelled";
        };
    }
 
    public static void main(String[] args) {
        System.out.println(messageFor(OrderStatus.SHIPPED));
    }
}

Common Beginner Mistakes

Comparing with == vs equals

Both work for enum constants (singleton instances). Prefer == for enums; use equals when accepting unknown types from strings after valueOf.

Relying on ordinal() for Business Logic

Order of declaration can change. Store explicit int level fields instead.

Public Enum Constructor

Enum constructors must be private (or package-private). Constants are created by the compiler.

Mini Practice

Create Planet enum with name and gravity field; loop values() and print each.

What’s Next

Reuse behavior with Inheritance and Abstract Classes.

FAQ

Is enum a class?

Yes. Each constant is a public static final instance of the enum type.

Can enums extend other classes?

No multiple inheritance—enums implicitly extend java.lang.Enum. They can implement interfaces.

When should I use enum vs static final constants?

Use enum when you have a fixed set with behavior or safe switching. Simple int constants are rare in modern Java style.

Can I use enum in generics?

Yes: Map<OrderStatus, String>.

How do enums relate to record?

Both model domain concepts; enums are for fixed variants, records for data snapshots.