Commit c314c30
committed
feat(generics): implement Box<T extends Number> class with bounded type parameter
WHAT:
- Created a generic class `Box<T>` that accepts only subclasses of `Number` (e.g., Integer, Double, Float).
- Added constructor for initialization, along with getter and setter methods.
WHY:
- Demonstrates **bounded type parameters** in Java Generics.
- Restricts generic types to numeric classes, preventing invalid usages (e.g., Box<String> is not allowed).
- Ensures type safety while allowing flexibility with different numeric types.
HOW:
- Declared class as `Box<T extends Number>`.
- Provided constructor `Box(T value)` to initialize the box with a numeric type.
- Implemented `getValue()` and `setValue(T value)` for retrieving and modifying the stored value.
KEY POINTS:
- `T extends Number` means:
- `T` can be `Integer`, `Double`, `Float`, `Long`, etc. (all subclasses of `Number`).
- Enforces compile-time restriction → avoids misuse with non-numeric types.
- Without this bound, `Box<T>` would accept any type (including non-numeric ones).
BENEFITS:
- Enables safe numeric operations (e.g., `doubleValue()`, `intValue()`) since `Number` defines these methods.
- Prevents runtime errors by catching invalid type usage at compile-time.
- Makes the class reusable for different numeric scenarios (statistics, math utilities, etc.).
REAL-WORLD USE CASES:
- Generic mathematical containers that must only store numbers.
- Utility classes in frameworks dealing with measurements, coordinates, or statistics.
- Similar to how `java.util.Optional<T>` restricts null-handling, this restricts type usage.
EXAMPLE USAGE:
Box<Integer> intBox = new Box<>(10);
Box<Double> doubleBox = new Box<>(15.5);
System.out.println(intBox.getValue()); // 10
System.out.println(doubleBox.getValue()); // 15.5
// Box<String> strBox = new Box<>("Hello"); // Compile-time error
NOTES:
• Upper bounds (extends) are used for reading numeric values.
• Lower bounds (super) are used when we want to write values safely.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent b152e85 commit c314c30
1 file changed
+48
-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 | + | |
0 commit comments