In Java, an enum is a special data type used to define a fixed set of named constants, and under the hood every enum is compiled into a class that implicitly extends java.lang.Enum. The constants you list (like MONDAY or TUESDAY) are actually public static final instances of that class, created once when the enum is first loaded, which is why enums give you type-safe, singleton-like constants that can never be duplicated at runtime.
Background: Why Java Added Enums
Enums were introduced in Java 5 (released in 2004). Before that, developers模拟枚举 used the "typesafe enum pattern" with ordinary classes, or more commonly defined public static final int or String constants. Both approaches had problems:
- Int constants are not type-safe: any
intcan be passed where a weekday is expected, including values that don't exist. - Constant strings offer no compile-time checking and no namespace.
- Printing an int constant gives you a meaningless number, not a readable name.
- Switch statements over ints have no way to verify all cases are covered.
Java's enum design, largely credited to Joshua Bloch's work on the language, solved these issues by making enum constants real objects with names, ordering, and full class capabilities.
The Basic Syntax
The simplest enum lists constants separated by commas:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}You can then declare variables, compare with ==, and switch over them:
Day today = Day.MONDAY;
switch (today) {
case MONDAY -> System.out.println("Start of week");
case FRIDAY -> System.out.println("Almost weekend");
default -> System.out.println("Midweek");
}Because there is exactly one instance of each constant, == comparison is always safe and preferred over .equals() for enums.
What the Compiler Actually Generates
When you compile an enum, the compiler turns it into a final class that extends java.lang.Enum. For the Day example, the rough equivalent is:
- Each constant becomes
public static final Day MONDAY = new Day("MONDAY", 0);and so on, with an auto-incrementing ordinal. - A private constructor prevents you from creating new instances with
new. values()returns an array of all constants, andvalueOf(String)looks one up by exact name.- Serialization is specially handled so deserializing never produces a duplicate instance.
- Reflection-based creation of enum instances is blocked by the JVM.
This is why enum constants are guaranteed singletons even across serialization — a stronger guarantee than most hand-written singleton patterns provide.
Enums as Full Classes: Fields, Methods, and More
Unlike enums in C or C++, which are just named integers, Java enums are full classes. Each constant can carry data and behavior:
enum Planet {
MERCURY(3.3e23), EARTH(5.97e24);
private final double mass;
Planet(double mass) { this.mass = mass; }
public double mass() { return mass; }
}Key rules and capabilities:
- Constructors are always private (or package-private); you can never invoke them directly.
- Constants must be declared first, followed by a semicolon before fields and methods.
- Each constant can override methods with a constant-specific body.
- Enums can implement interfaces but cannot extend other classes (the slot is taken by
Enum). - They cannot be extended by other classes, since the compiler marks them final.
Useful Built-in Methods
name()— the constant's declared name as a String.ordinal()— its zero-based position in the declaration.values()— array of all constants (added by the compiler, not inherited from Enum).valueOf(String)— returns the constant matching an exact name; throwsIllegalArgumentExceptionif absent.compareTo()andgetDeclaringClass()— inherited from Enum.
Common Pitfalls and Problems
- Depending on
ordinal(): the ordinal is position-based, so inserting or reordering constants silently changes stored values. Storename()or an explicit field instead. valueOf()with user input: it throws on unknown names. Catch the exception or useArrays.stream(values())to search safely.- Switch exhaustiveness: traditional switch statements don't require covering every constant; newer Java versions (from Java 21, with pattern switches finalized) can check exhaustiveness for enum switches, including in switch expressions where it was required since Java 14.
- Adding constants later: new values can break code that assumed the old fixed set — a good reason to avoid default branches that silently swallow new cases.
When to Choose an Enum (and When Not To)
Choose an enum when the set of values is known at compile time and rarely changes: days, directions, card suits, status codes, operation types. Enums are also the recommended way to implement singletons in Java, since the JVM enforces uniqueness.
Consider alternatives when:
- The set of values must be extended at runtime or loaded from a database — use a class with a registry instead.
- You need integer compatibility with a wire protocol — pair the enum with an explicit numeric field.
- The value is really a configurable option, not a fixed category — constants or configuration may fit better.
How Java Enums Compare to Other Languages
In C and C++, an enum is essentially a list of named integers with no type enforcement beyond weak checks, and you can assign arbitrary ints to enum variables. C#'s enums are closer to C's (integer-backed, no per-constant data), though with better type safety. Kotlin reuses Java's enum type directly. Python's Enum (added in Python 3.4) was inspired by Java's design and also supports methods and fields. Java's approach — enum as a full class with enforced singletons — remains one of the richest implementations among mainstream languages.
Frequently Asked Questions
Can I use enum in a switch statement?
Yes, and it's one of the most common uses. Inside a switch, you use the bare constant names (case MONDAY), not Day.MONDAY. Since each constant is a singleton, the compiler can compile enum switches into efficient table lookups based on ordinal values.
Why can't I extend an enum class?
Every enum implicitly extends java.lang.Enum, and Java allows only single inheritance, so the superclass slot is already used. The compiler also marks enums final, so nothing can extend them. To share behavior, implement an interface and attach it to multiple enums instead.
Is an enum a good way to implement a singleton?
Yes — it's the approach Joshua Bloch recommends in Effective Java. An enum with one constant gives you a singleton that is thread-safe by default and safe against serialization and reflection attacks, which hand-written singletons often are not.
What happens if I serialize an enum?
Only the constant's name is written, not the object state. On deserialization, the JVM returns the existing constant rather than creating a new object, so == comparisons still work after a round trip.
Can I add new constants to an enum without breaking code?
Usually yes, but watch for three risks: code that assumes a fixed number of values (e.g., arrays indexed by ordinal), switch statements with a default branch that hides the new case, and serialized or persisted values that depend on ordering. Adding constants is generally safer than renaming or removing them.
Are enum constants created lazily?
No. All constants are instantiated eagerly when the enum class is initialized — the first time the class is actively used. This happens in a single class-initialization step, which is thread-safe by JVM rules, so you never need to worry about concurrent creation.