Enum Fields and Constructors

Java enum constants can store their own state through fields initialized by an enum constructor. This lets each constant carry data and behavior while keeping the set of valid values fixed.

An enum can declare fields just like a class. Each enum constant can provide arguments when it is declared, and those arguments are passed to the enum's constructor.

Enum constructors are implicitly private; an enum cannot be instantiated with `new` from outside its declaration. The constructor initializes fields for the predefined enum instances.

A common pattern is to give each constant a property such as a numeric code or display name, then expose it through a method. The fields are typically `private` and are often `final` when their values should not change.

For example, `Status.OK(200)` passes `200` to the enum constructor, so the `OK` constant stores that value. The same constructor can initialize the corresponding field for every constant, using different arguments.

Key points

Interview questions

What happens when an enum constant has constructor arguments?

The arguments are used when the enum constants are initialized. They are passed to the enum's constructor, which assigns them to the appropriate fields. Each constant therefore retains the state established by its own arguments.

Can an enum have fields and constructors in Java?

Yes. An enum can declare fields, methods, and a constructor. Each constant can pass arguments to that constructor when the enum is declared. The constructor initializes the state associated with that constant.

Why are enum constructors private?

Enum constructors are not intended to be called by application code. The enum declaration controls which instances exist, so callers cannot create additional enum instances with `new`. The constants declared by the enum are the instances available to code using that enum.

How would you associate a numeric code with each enum constant?

Declare a field for the code and initialize it through the enum constructor. Each constant supplies its code as an argument in the declaration. If the code should not change, make the field `private final` and provide a method to read it.