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

Initializing Enum Constants with Constructor Arguments

Practice passing arguments to enum constructors when declaring constants to set field values.

Initializing Enum Constants with Constructor Arguments

What you'll learn: How to pass values to an enum constructor when declaring each constant to set that constant's fields.

In the previous lesson, you learned that enums can have constructors. Now comes the practical part: actually using those constructors when you declare your enum constants. Each constant can pass different arguments to initialize its own field values, making each constant unique beyond just its name.

The Syntax

When declaring an enum constant, you write its name followed by parentheses containing the arguments you want to pass to the constructor. This happens right at the moment you list your constants:

public enum Size {
    SMALL(10),
    MEDIUM(20),
    LARGE(30);
    
    private final int value;
    
    Size(int value) {
        this.value = value;
    }
    
    public int getValue() {
        return value;
    }
}

Notice how SMALL(10) passes 10 to the constructor, MEDIUM(20) passes 20, and so on. Each constant gets its own value field initialized differently.

Multiple Arguments Work Too

Your constructor can accept multiple parameters:

public enum Planet {
    EARTH(5.976e24, 6.37814e6),
    MARS(6.421e23, 3.3972e6);
    
    private final double mass;
    private final double radius;
    
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
}

Think of It Like This

Declaring SMALL(10) is like saying "create a Size object called SMALL by calling new Size(10)"—except the enum does this automatically at class-loading time, and you can't call new yourself.

Key Takeaway: Pass arguments in parentheses after each enum constant's name to initialize that constant's fields via its constructor—each constant can have different values.