Commit 9c215df
committed
feat(generic-interface): add example of bounded type parameters with class and interface constraints
WHAT:
- Introduced `Printable` interface with a `print()` method.
- Implemented `MyNumber` class extending `Number` and implementing `Printable`.
- Created a generic class `Box<T extends Number & Printable>`:
- Restricts type parameter `T` to extend `Number` and also implement `Printable`.
- Demonstrates that class must come first, followed by interfaces when declaring multiple bounds.
- Added `Test` class to show usage of `Box<MyNumber>`.
WHY:
- Demonstrates how to enforce multiple constraints on generic type parameters in Java.
- Shows real-world relevance where a type must satisfy both numeric behavior (via `Number`) and custom contract (via `Printable`).
DETAILS:
- `MyNumber` overrides `Number` methods (`intValue`, `longValue`, `floatValue`, `doubleValue`) and adds a custom print.
- `Box<T>` stores a bounded type, ensures type safety, and allows invoking both `Number` methods and `Printable` methods.
- In `main()`, a `Box<MyNumber>` object is created and `display()` calls the `print()` method.
KEY LEARNING:
- Multiple bounds in generics are declared using `&`.
- Rule: A class must appear first, followed by any number of interfaces.
- This ensures strong type safety while allowing rich polymorphism.
BENEFITS:
- Enforces contracts at compile-time rather than relying on runtime checks.
- Makes code reusable, type-safe, and flexible.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 01dc531 commit 9c215df
1 file changed
+94
-0
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
| 17 | + | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 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 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
| 67 | + | |
| 68 | + | |
| 69 | + | |
| 70 | + | |
| 71 | + | |
| 72 | + | |
| 73 | + | |
| 74 | + | |
| 75 | + | |
| 76 | + | |
| 77 | + | |
| 78 | + | |
| 79 | + | |
| 80 | + | |
| 81 | + | |
| 82 | + | |
| 83 | + | |
| 84 | + | |
| 85 | + | |
| 86 | + | |
| 87 | + | |
| 88 | + | |
| 89 | + | |
| 90 | + | |
| 91 | + | |
| 92 | + | |
| 93 | + | |
| 94 | + | |
0 commit comments