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:
Enum with Multiple Fields and Methods
✔ Output:
Enum with Custom Method Behavior
✔ Output:
🏁 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.
