Course contentsShow
← Java
Lesson 588 of 2,87014. EnumerationsFree lesson

Enum Constructors: Syntax and Restrictions

Understand how enum constructors work, why they must be private, and how they initialize each constant.

Enum Constructors: Syntax and Restrictions

What you'll learn: How enum constructors work behind the scenes, why they must be private, and how they initialize each constant with custom values.

The Core Idea

Every enum constant you declare is actually an instance of that enum type. Just like regular classes, enums can have constructors to initialize their fields. However, enum constructors have special rules: they must be private (or have default/package-private access, which Java treats as private for enums), and you cannot call them directly with new.

Think of it this way: when you declare enum constants, Java is secretly calling the constructor for you. The enum constants at the top are like pre-built, unchangeable objects that get created once when the class loads.

How Enum Constructors Work

When you declare fields in an enum, you need a constructor to set those values. Here's the syntax:

public enum Size {
    SMALL(10),    // Calls Size(10)
    MEDIUM(20),   // Calls Size(20)
    LARGE(30);    // Calls Size(30)

    private int value;

    // Constructor - must be private (or default)
    private Size(int value) {
        this.value = value;
    }

    public int getValue() {
        return value;
    }
}

Each constant passes arguments in parentheses, which are forwarded to the constructor. The constructor then initializes the fields.

Why Private?

Enum constructors must be private because enums represent a fixed set of constants. If you could call new Size(40) from outside, you'd break the fundamental guarantee that enums are limited, controlled sets of values. Java enforces this restriction automatically—even if you omit the private keyword, the constructor cannot be called from outside the enum.

Key Takeaway: Enum constructors initialize each constant's fields and must be private to prevent external instantiation, ensuring your enum remains a fixed, controlled set of values.