Commit 9866223
committed
feat: add Enum example demonstrating toString(), name(), and values()
WHAT was added:
- Created an enum `Size` with constants: SMALL, MEDIUM, LARGE, EXTRALARGE.
- Overrode `toString()` specifically for `SMALL` to print "Pizza is small".
- Demonstrated:
- `toString()` for custom string output.
- `name()` to fetch the exact declared identifier.
- `values().length` to count enum constants.
WHY this matters:
- Enums in Java are type-safe constants, better than using raw `int` or `String` constants.
- Demonstrates the difference between:
- `toString()` → customizable, can be overridden per constant.
- `name()` → fixed, always returns the declared constant name.
- `values()` is a handy utility to iterate over all enum constants or count them.
HOW it works:
1. `Size.SMALL.toString()` prints "Pizza is small" (overridden).
2. `Size.MEDIUM.name()` prints "MEDIUM" (exact enum identifier).
3. `Size.values().length` prints `4` (total number of constants).
REAL-LIFE APPLICATIONS:
- Pizza ordering system → `Size.SMALL`, `Size.MEDIUM`, etc.
- Traffic lights → `enum Signal { RED, YELLOW, GREEN }`.
- Payment status → `enum Status { PENDING, SUCCESS, FAILED }`.
- Logging levels → `enum LogLevel { INFO, WARN, ERROR }`.
- Role-based access control → `enum Role { ADMIN, USER, GUEST }`.
COMPARISON:
- `toString()` → can be overridden for user-friendly messages (UI display).
- `name()` → always returns constant’s code representation (useful for debugging, persistence).
- `ordinal()` (not shown here) → gives numeric index (but not recommended for persistence as ordering may change).
KEYWORDS:
enum, toString override, name method, values method, type-safe constants, real-world enum use cases.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 7c50554 commit 9866223
1 file changed
+28
-9
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
9 | 11 | | |
| 12 | + | |
10 | 13 | | |
11 | | - | |
12 | | - | |
| 14 | + | |
13 | 15 | | |
14 | 16 | | |
15 | 17 | | |
16 | 18 | | |
17 | 19 | | |
18 | 20 | | |
19 | | - | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
0 commit comments