Skip to main content
Java

Understanding Java Enum Constructors: Beyond Basic Constants

4 mins

Constructor workman representing constructors in Java.

Java Enums - The VIP List of Constants #

Think of enums in Java like the ultimate VIP list: a special data type that lets you neatly package up a set of constants in one place. Instead of scattering values around your code, you get to group related constants together and keep things clean and tidy. Here’s how you define an enum in Java:

public enum MonitorResolution {
    HD, FULL_HD, FOUR_K, FIVE_K
}

Want to use it? Just call it like this:

MonitorResolution resolution = MonitorResolution.FULL_HD;

And voilà, you’re speaking to your constants directly. No muss, no fuss. Just a team of values, organized and ready for duty.

Why Enums Are Your Best Friend #

Enums make it easy to reference related constants in a way that’s intuitive and typo-proof, especially with modern IDEs helping you along with auto-complete. They’re great when you have a fixed set of values that should stay together, ready to pass as method arguments without all the mystery and errors.

Enums in Action: If-Else Statements #

Picture a method that calculates pixel counts based on a monitor’s resolution. Sure, you could roll with a series of if-else statements like this:

public long pixelCount(MonitorResolution resolution) {
    if (resolution == MonitorResolution.HD) {
        return 1280 * 720;
    } else if (resolution == MonitorResolution.FULL_HD) {
        return 1920 * 1080;
    } else if (resolution == MonitorResolution.FOUR_K) {
        return 3840 * 2160;
    } else if (resolution == MonitorResolution.FIVE_K) {
        return 5120 * 2880;
    }
}

Or, Switch It Up #

Alternatively, go for a switch statement to keep things clean and readable:

public long pixelCount(MonitorResolution resolution) {
    switch (resolution) {
        case HD:
            return 1280 * 720;
        case FULL_HD:
            return 1920 * 1080;
        case FOUR_K:
            return 3840 * 2160;
        case FIVE_K:
            return 5120 * 2880;
    }
}

The catch? Every time you add a new resolution type, you’ll need to update each if-else or switch statement individually. This quickly turns into a nightmare if multiple methods rely on your enum.

Adding Constructors to Enums – The Pro Move #

enums are a type of Java Class

Now, let’s unlock the true potential of enums by adding constructors. Enums in Java are essentially classes, so they can have fields, methods, and yes—constructors. This lets you attach specific attributes to each constant and streamline your code for fewer bugs and better readability.

Here’s how you’d add constructors and fields to an enum:

public enum MonitorResolution {
    HD(1280, 720),
    FULL_HD(1920, 1080),
    FOUR_K(3840, 2160),
    FIVE_K(5120, 2880);

    private final int width;
    private final int height;

    MonitorResolution(int width, int height) {
        this.width = width;
        this.height = height;
    }

    public int getWidth() {
        return width;
    }

    public int getHeight() {
        return height;
    }
}

And with that, your pixelCount method becomes as simple as:

public long pixelCount(MonitorResolution resolution) {
    return resolution.getWidth() * resolution.getHeight();
}

Now, if you decide to add an 8K resolution, just update the enum, and you’re all set. No extra code scattered across methods, no headaches.

public enum MonitorResolution {
    HD(1280, 720),
    FULL_HD(1920, 1080),
    FOUR_K(3840, 2160),
    FIVE_K(5120, 2880),
    EIGHT_K(7680, 4320); // new resolution

    // rest of the code
}

Rules of the Enum Constructor #

Though enums are class-like, there are some ground rules for their constructors:

  • The constructor must be private or package-private.
  • The constructor cannot be invoked directly, Java will automatically call the constructor when the enum constants are created.

The last rule may seem like a restriction, but it is actually a feature. It ensures that the enum constants are created only once, saving memory, and if the constructor is private, it prevents the creation of new instances of the enum constants.

Adding Methods Directly to Enums #

Why stop at fields and constructors? You can even add methods right inside the enum. For instance, let’s make pixelCount() a method within MonitorResolution:

public enum MonitorResolution {
    HD(1280, 720),
    FULL_HD(1920, 1080),
    FOUR_K(3840, 2160),
    FIVE_K(5120, 2880);

    // existing fields and constructor...

    public long pixelCount() {
        return width * height;
    }
}

Now, calculating pixel count is as simple as calling pixelCount() directly on an enum constant:

MonitorResolution resolution = MonitorResolution.FULL_HD;
long pixelCount = resolution.pixelCount();

long anotherPixelCount = MonitorResolution.FOUR_K.pixelCount();

As you can iterate over enums, using the values() method, a method that calculates the largest pixel count across all resolutions is a breeze, and is automatically updated when you add new resolutions.

public long largestPixelCount() {
    long max = 0;
    for (MonitorResolution resolution : MonitorResolution.values()) {
        max = Math.max(max, resolution.pixelCount());
    }
    return max;
}

Wrapping Up #

Using constructors in enums doesn’t just eliminate the tedium of endless if-else blocks; it brings clarity and flexibility to your code. With this approach, every new constant you add becomes automatically functional across your code, making for a cleaner, bug-free experience. So next time, let your enums do the heavy lifting—and keep your code as sharp as an 8K display.