Commit 3659898
committed
refactor(generic-types): replace Object-based Box with type-safe generic BoxIMP<T>
WHAT:
- Introduced `BoxIMP<T>` class using generics instead of raw `Object`.
- Getter and setter methods now operate directly on the type parameter `T`.
- Updated `Main` to demonstrate safe usage with `BoxIMP<Integer>`.
WHY:
- The earlier `Box` implementation required casting (`(String) box.getValue()`)
which caused runtime `ClassCastException`.
- Generics enforce compile-time type safety, eliminating the need for unsafe casts.
- Improves readability, maintainability, and robustness of the code.
HOW:
- Defined class as `public class BoxIMP<T>`.
- `setValue(T value)` ensures only correct type can be stored.
- `getValue()` returns `T` directly, avoiding explicit casting.
- Example: `BoxIMP<Integer>` ensures only integers can be set and retrieved safely.
BENEFITS:
- Prevents runtime casting errors by shifting checks to compile time.
- Cleaner, more expressive code (`BoxIMP<Integer>` vs `Box` with Object).
- Reusable for multiple types (e.g., `BoxIMP<String>`, `BoxIMP<Double>`).
REAL-WORLD APPLICATION:
- Similar to how Java Collections Framework uses generics (e.g., `List<String>`).
- Useful in designing APIs or libraries where container classes must be flexible but type-safe.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 71844de commit 3659898
1 file changed
+13
-7
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | 4 | | |
8 | 5 | | |
9 | 6 | | |
| |||
18 | 15 | | |
19 | 16 | | |
20 | 17 | | |
| 18 | + | |
21 | 19 | | |
| 20 | + | |
22 | 21 | | |
23 | 22 | | |
24 | 23 | | |
25 | 24 | | |
26 | 25 | | |
27 | 26 | | |
28 | | - | |
29 | | - | |
| 27 | + | |
| 28 | + | |
| 29 | + | |
| 30 | + | |
| 31 | + | |
| 32 | + | |
| 33 | + | |
| 34 | + | |
30 | 35 | | |
31 | | - | |
| 36 | + | |
| 37 | + | |
32 | 38 | | |
33 | 39 | | |
34 | 40 | | |
35 | | - | |
| 41 | + | |
0 commit comments