Backend Development 9 min read

Master Java Enums: Eliminate if/else and Boost Code Quality

This article revisits Java's enum type, explaining its definition, constructors, methods, and practical uses such as replacing if/else logic, implementing interfaces, enhancing type safety, and applying enums in switch statements and singleton patterns, complete with code examples and best‑practice tips.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Master Java Enums: Eliminate if/else and Boost Code Quality

Definition

In mathematics and computer science, an enumeration lists all members of a finite set. In Java, an

enum

is a named collection of constant values. For example, a week can be represented as:

<code>public enum Week {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}</code>

Enum constants are instances of the enum type and cannot be created with

new

. They are accessed as

Week.SUNDAY

, etc.

Constructors

Enum types can have constructors, which are implicitly

private

. A no‑argument constructor runs once for each enum constant:

<code>public enum Week {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;

    Week() {
        System.out.println("hello");
    }
}</code>

When the enum is loaded, the constructor prints "hello" seven times, once for each constant.

Parameterized Constructors

Enums can also have constructors with parameters, allowing each constant to carry additional data:

<code>public enum Week {
    SUNDAY(7), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    private int weekNum;
    Week(int weekNum) {
        System.out.println(weekNum);
    }
}</code>

This prints

7 1 2 3 4 5 6

during initialization.

Enum Members

Enums can declare fields, instance methods, and static methods just like regular classes:

<code>public enum Week {
    SUNDAY(7), MONDAY(1), TUESDAY(2), WEDNESDAY(3), THURSDAY(4), FRIDAY(5), SATURDAY(6);

    private int weekNum;
    Week(int weekNum) { this.weekNum = weekNum; }
    public int getWeekNum() { return weekNum; }
}</code>

Usage example:

<code>public class Test {
    public static void main(String[] args) {
        Week w = Week.FRIDAY;
        System.out.println(w.getWeekNum()); // prints 5
    }
}</code>

values() and valueOf(String)

static Week[] values()

returns an array of all enum constants.

static Week valueOf(String name)

returns the constant whose name matches the supplied string.

<code>for (Week w : Week.values()) {
    System.out.println(w);
}
System.out.println("Sunday: " + Week.valueOf("SUNDAY"));</code>

Output:

SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY Sunday: SUNDAY

Practical Uses

Type Safety

Using enums instead of raw

double

constants provides compile‑time type safety. For example, a discount can be defined as:

<code>public enum Discount {
    EIGHT_DISCOUNT(0.8), SIX_DISCOUNT(0.6), FIVE_DISCOUNT(0.5);
    private double discountNum;
    Discount(double discountNum) { this.discountNum = discountNum; }
    public double getDiscountNum() { return discountNum; }
}</code>
<code>public static BigDecimal calculatePrice(Discount discount) {
    System.out.println(discount.getDiscountNum());
    return null; // actual calculation omitted
}
</code>

Switch Statements

<code>Week w = Week.MONDAY;
switch (w) {
    case MONDAY: System.out.println("周一"); break;
    case TUESDAY: System.out.println("周二"); break;
}
</code>

Implementing Interfaces to Remove if/else

Define an interface with a common method and let each enum constant provide its own implementation:

<code>public interface Eat { String eat(); }

public enum AnimalEnum implements Eat {
    Dog { public void eat() { System.out.println("吃骨头"); } },
    Cat { public void eat() { System.out.println("吃鱼干"); } },
    Sheep { public void eat() { System.out.println("吃草"); } };
}
</code>

Calling code becomes a single line:

<code>AnimalEnum.valueOf("Cat").eat(); // prints 吃鱼干
</code>

Singleton Pattern via Enum

<code>public class SingletonExample {
    private SingletonExample() {}
    public static SingletonExample getInstance() {
        return Singleton.INSTANCE.getInstance();
    }
    private enum Singleton {
        INSTANCE;
        private final SingletonExample instance = new SingletonExample();
        public SingletonExample getInstance() { return instance; }
    }
}
</code>

Summary

Java also provides specialized collections for enums, such as

EnumSet

and

EnumMap

. While enums are powerful, they have limitations; see the linked discussion for drawbacks.

design patternsJavaEnumtype safetyif-else
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.