Skip to Content
Course content

36: Enum Methods and Constructors

Click on the "Edit" button in the top corner of the screen to edit your slide content.

A lot of people treat Enums as if they're just a more readable version of public static final int. I've seen countless developers use them purely as a list of names—like a menu—without realizing that in Java, an Enum is actually a specialized class. The most common misconception I encounter is the belief that Enums cannot hold state or have constructors because "you can't instantiate a constant."

If you think an Enum is just a label, you're missing out on the most powerful part of the feature. Let's look at why that "constants-only" mindset is wrong. Imagine you're building a system to handle shipping speeds.

// The "Limited" way - just labels
public enum ShippingSpeed {
    STANDARD, EXPRESS, OVERNIGHT
}

// To actually use these, you'd end up writing clunky switch statements everywhere:
public double getCost(ShippingSpeed speed) {
    switch(speed) {
        case STANDARD: return 5.0;
        case EXPRESS: return 15.0;
        case OVERNIGHT: return 30.0;
        default: throw new IllegalArgumentException();
    }
}

This works, but it's brittle. Every time you add a new shipping speed, you have to hunt down every switch statement in your codebase to update the costs. It's a maintenance nightmare.

From Simple Labels to Stateful Objects

The correction is simple: give the Enum the data it needs. Because Enums are classes, they can have fields, and those fields can be initialized via a constructor. The trick is that the Enum constructor is called internally by the JVM when the constants are created. You don't call new ShippingSpeed()—in fact, you can't—but the JVM does it for you.

public enum ShippingSpeed {
    // These are actually calls to the constructor below!
    STANDARD(5.0, 5), 
    EXPRESS(15.0, 2), 
    OVERNIGHT(30.0, 1);

    private final double price;
    private final int daysToDeliver;

    // The constructor MUST be private (or package-private). 
    // Java won't even let you make it public.
    ShippingSpeed(double price, int daysToDeliver) {
        this.price = price;
        this.daysToDeliver = daysToDeliver;
    }

    public double getPrice() {
        return price;
    }

    public int getDaysToDeliver() {
        return daysToDeliver;
    }
}

Now, that clunky switch statement from earlier disappears. Instead of asking a helper method what the cost of STANDARD is, you just ask the object itself: ShippingSpeed.STANDARD.getPrice(). I always recommend this approach because it keeps the data and the logic in one place.

Adding Behavior with Enum Methods

Beyond just storing data, you can add actual logic to your Enums. You can write methods that perform calculations based on the internal state of the constant. This transforms your Enum from a data container into a behavioral object.

Let's say we want to calculate the total cost including a luxury tax for faster shipping. We can add a method directly into the Enum:

public enum ShippingSpeed {
    STANDARD(5.0, 5), 
    EXPRESS(15.0, 2), 
    OVERNIGHT(30.0, 1);

    private final double price;
    private final int daysToDeliver;

    ShippingSpeed(double price, int daysToDeliver) {
        this.price = price;
        this.daysToDeliver = daysToDeliver;
    }

    public double calculateTotalWithTax(double taxRate) {
        // Only apply tax to speeds faster than STANDARD
        if (this == STANDARD) {
            return price;
        }
        return price * (1 + taxRate);
    }
}

Note how I used this == STANDARD. Inside an Enum method, this refers to the specific constant being operated on. It's a clean, object-oriented way to handle variation without sprawling if-else blocks across your service layer.




📋 Practical Task

Implementing a Game Difficulty XP Modifier

You are building a combat system for an RPG. Different difficulty levels should provide different amounts of Experience Points (XP) to the player. Instead of using a series of if statements in your Player class, you will implement a DifficultyLevel Enum to handle the logic.

Requirements:

  • Create an Enum named DifficultyLevel.
  • Add three constants: EASY, NORMAL, and HARD.
  • Add a private final field double xpMultiplier.
  • Implement a constructor that assigns the multiplier:
    • EASY: 0.5x
    • NORMAL: 1.0x
    • HARD: 1.5x
  • Add a method called calculateXp(int baseXp) that returns the baseXp multiplied by the xpMultiplier (cast the result to an int).

Testing your code: In your main method, verify that DifficultyLevel.HARD.calculateXp(100) returns 150.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.