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:

public enum Week {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

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:

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

    Week() {
        System.out.println("hello");
    }
}

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:

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);
    }
}

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:

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; }
}

Usage example:

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

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.

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

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:

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; }
}
public static BigDecimal calculatePrice(Discount discount) {
    System.out.println(discount.getDiscountNum());
    return null; // actual calculation omitted
}

Switch Statements

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

Implementing Interfaces to Remove if/else

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

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("吃草"); } };
}

Calling code becomes a single line:

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

Singleton Pattern via Enum

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; }
    }
}

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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

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

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.