Master Java Enums: From Basics to Advanced Real-World Patterns
This article introduces a Spring Boot 3 case collection and provides a comprehensive guide to Java enums, covering their definition, type safety, custom values, interface implementation, abstract methods, generics, pattern matching, functional programming, collection usage, and sealed‑class integration with clear code examples.
1. Introduction
Java enums (Enum) are special classes that represent a fixed set of constants, providing type safety, readable names, and the ability to include fields, methods, and constructors.
<code>public enum Singleton {
//唯一的枚举实例
INSTANCE;
//添加单例类需要的功能方法
public void action() {
// ...
}
}
Singleton singleton = Singleton.INSTANCE;
singleton.action();</code>When constants are defined with plain static final ints, the code lacks type safety and meaningful output.
<code>public class OrderStatus {
public static final int PENDING = 1;
public static final int PROCESSING = 2;
public static final int COMPLETED = 3;
public static final int CANCELLED = 4;
}</code>Type‑unsafe: any int can be assigned.
Printing shows numeric values instead of names.
Enums solve these problems by being type‑safe and providing meaningful names.
<code>public enum OrderStatus {
PENDING, PROCESSING, COMPLETED, CANCELLED;
}</code>2. Practical Cases
2.1 Enum with custom constant values
<code>public enum OrderStatus {
PENDING(1), PROCESSING(2), COMPLETED(3), CANCELLED(4);
private int value;
private OrderStatus(int value) { this.value = value; }
public int getValue() { return value; }
}</code>The constructor must be private; a public getter exposes the associated value.
2.2 Enum implementing an interface
<code>public enum OrderStatus implements Runnable {
PENDING(1), PROCESSING(2), COMPLETED(3), CANCELLED(4);
@Override
public void run() {
// TODO
}
}</code>2.3 Enum with abstract method
<code>public enum FileFormat {
JSON {
public String serialize(Object data) { return "JSON: " + data.toString(); }
},
XML {
public String serialize(Object data) { return "XML: " + data.toString(); }
};
public abstract String serialize(Object data);
}</code>2.4 Enum with generics
<code>public enum Converter {
INTEGER {
public Integer convert(String value) { return Integer.parseInt(value); }
},
DOUBLE {
public Double convert(String value) { return Double.parseDouble(value); }
};
public abstract <T> T convert(String value);
}</code>2.5 Enum with pattern matching (switch)
<code>public enum Status { INITIALIZED, RUNNING, COMPLETED, FAILED }
public class ProcessHandler {
public static String handleStatus(Status status) {
return switch (status) {
case INITIALIZED -> "Process is initialized.";
case RUNNING -> "Process is running.";
case COMPLETED -> "Process completed successfully.";
case FAILED -> "Process failed!";
};
}
}</code>2.6 Enum with functional programming
<code>public enum Transformer {
UPPER(s -> s.toUpperCase()),
LOWER(s -> s.toLowerCase()),
REVERSE(s -> new StringBuilder(s).reverse().toString());
private final Function<String, String> transform;
Transformer(Function<String, String> transform) { this.transform = transform; }
public String apply(String input) { return transform.apply(input); }
}</code>2.7 Enum with collections
<code>public enum OrderStatus {
PENDING(1), PROCESSING(2), COMPLETED(3), CANCELLED(4);
private int value;
private OrderStatus(int v) { this.value = v; }
public static void main(String[] args) {
EnumSet<OrderStatus> set = EnumSet.allOf(OrderStatus.class);
set.forEach(s -> System.err.printf("%s → %d%n", s, s.value));
EnumMap<OrderStatus, Object> map = new EnumMap<>(OrderStatus.class);
map.put(PENDING, "Processing...");
map.forEach((s, o) -> System.err.println(s + "@" + o));
}
}</code>2.8 Enum with sealed classes (Java 17+)
<code>sealed interface Shape permits Circle, Rectangle { double area(); }
public enum Circle implements Shape {
UNIT_CIRCLE(1.0);
private final double radius;
Circle(double r) { this.radius = r; }
public double area() { return Math.PI * radius * radius; }
}
public enum Rectangle implements Shape {
SQUARE(1.0, 1.0);
private final double width;
private final double height;
Rectangle(double w, double h) { this.width = w; this.height = h; }
public double area() { return width * height; }
}</code>Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.