Java Enum Constructor

Java Enum Constructor

In Java, an enum can have a constructor, just like a class.
However:

✔ The constructor must be private (or default).
❌ It cannot be public or protected.
✔ It is used to assign custom values to enum constants.

When you define an enum with parameters, the constructor runs automatically when each constant is created.


Example: Enum with Constructor


 

✔ Output:

S
XL

Enum with Multiple Fields and Methods


 

✔ Output:

MERCURY -> Mass: 3.3 ×10^24 kg, Radius: 2439 km
EARTH -> Mass: 5.97 ×10^24 kg, Radius: 6371 km
MARS -> Mass: 0.642 ×10^24 kg, Radius: 3389 km

Enum with Custom Method Behavior


 

✔ Output:

200 -> Operation Successful
500 -> Error Occurred

🏁 Key Rules About Enum Constructor

Rule Description
Cannot be public Must be private or default
Called automatically Runs once per enum constant
Used for initializing values Similar to class fields

🎉 Summary

  • Enum constructors allow adding custom data to enum constants.

  • They run automatically when the enum is loaded.

  • Enums can also contain getters, methods, and abstract behavior.

You may also like...