📘 Java Enums with Constructors — A Simple & Clear Guide
Enums in Java are often misunderstood as simple lists of constants.
But Enums are actually powerful types — they can include fields, methods, and even constructors.
In this blog, we’ll explore how to use Enum constructors to attach data to each enum constant.
We’ll also walk through an example where each subject has a maximum mark.
✅ What Are Enums in Java?
enum stands for enumeration, and it represents a fixed set of constants.
Example:
But Java enums are much more than constants.
They are full-fledged classes with:
-
Variables (fields)
-
Methods
-
Constructors
🎯 Why Use Constructors in Enums?
Sometimes, each enum constant needs to hold some extra information.
For example:
-
Days of week → working hours
-
Planets → mass, radius
-
Subjects → maximum marks
By using a constructor inside an enum, we can store additional data for each constant.
🧩 Example Use Case: Subjects and Maximum Marks
Suppose you want to store maximum marks for each subject:
| Subject | Code | Maximum Mark |
|---|---|---|
| Physics | P | 50 |
| Chemistry | C | 50 |
| Biology | B | 75 |
| Math | M | 100 |
Instead of using separate variables or maps, we attach values directly to enum constants.
🧱 Text Diagram: How Enum with Constructor Works
Each constant calls the constructor with a different value.
🧑💻 Full Java Code Example
🟦 Explanation
🔹 1. Enum Constants with Values
Each constant calls the constructor with a number (max mark).
🔹 2. Constructor
This assigns the passed value to the internal variable.
🔹 3. Getter Method
Used to read the stored value.
🖨️ Program Output
🎉 Final Thoughts
Java Enums are more powerful than most people realize.
By adding constructors and fields, you can treat them like lightweight data holders — clean, readable, and type-safe.
This approach is perfect for:
✔ Subject mark mapping
✔ Error codes with descriptions
✔ HTTP status codes
✔ Pricing tiers
✔ Role definitions
No comments:
Post a Comment