Commit 4dd7d05
committed
feat: demonstrate enum declaration inside and outside a class in Java
WHAT was added:
- Created a global enum `Color { RED, GREEN, BLUE }` and used it in `Enum3`.
- Demonstrated declaring an enum *inside* a class (`Enum4`) and using it similarly.
- Printed enum constants to show usage.
WHY this matters:
- Enums in Java can be declared at **top-level** (outside classes) or as **nested types** (inside a class).
- Helps developers understand valid scopes for enums:
- Outside any class (global scope).
- Inside a class (nested enum).
- Not allowed inside a method.
HOW it works:
- `Enum3` uses a globally declared enum `Color`.
- `Enum4` declares its own nested `Color` enum and references it within `main()`.
- Both approaches allow constants to be accessed as `Color.RED`.
REAL-LIFE APPLICATIONS:
- Top-level enums → shared across packages, e.g., `Status { PENDING, RUNNING, COMPLETED }`.
- Nested enums → tied to a specific class context, e.g.:
- `Order.State { NEW, PROCESSING, DELIVERED }` inside `Order` class.
- `TrafficLight.Color { RED, YELLOW, GREEN }` inside `TrafficLight` class.
NOTES / BEST PRACTICES:
1. Enum constants are implicitly `public static final`.
2. Enums should be named in singular form (`Color` instead of `Colors`).
3. Constants should follow UPPERCASE naming convention (`RED, GREEN, BLUE`).
4. Avoid declaring enums inside methods — this is not supported in Java.
5. Use top-level enums when they are reused widely, and nested enums when they are strongly coupled to a single class.
KEYWORDS:
enum, nested enum, top-level enum, declaration rules, type-safe constants.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 132e986 commit 4dd7d05
1 file changed
+29
-13
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | 1 | | |
8 | 2 | | |
9 | 3 | | |
10 | 4 | | |
11 | 5 | | |
| 6 | + | |
12 | 7 | | |
13 | | - | |
14 | 8 | | |
15 | 9 | | |
16 | 10 | | |
17 | 11 | | |
18 | 12 | | |
19 | 13 | | |
20 | 14 | | |
21 | | - | |
22 | | - | |
23 | | - | |
24 | | - | |
| 15 | + | |
| 16 | + | |
25 | 17 | | |
26 | 18 | | |
27 | 19 | | |
28 | 20 | | |
29 | | - | |
30 | 21 | | |
31 | 22 | | |
32 | 23 | | |
33 | 24 | | |
34 | | - | |
| 25 | + | |
| 26 | + | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
| 35 | + | |
| 36 | + | |
| 37 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
0 commit comments