Commit 9a63eb1
committed
feat: implement bounded type parameters in a generic Box class
WHAT:
- Added `Box<T extends Number>` class in `BoundedTypesinInterfaces` package.
- Created `Main.java` to demonstrate usage of bounded generics.
- Restricted type parameter `T` to subclasses of `Number` (e.g., Integer, Float, Double).
- Showed compile-time error when attempting to use a non-Number type (e.g., String).
HOW:
1. `Box<T extends Number>`:
- Declares a generic class where `T` must be a subclass of `java.lang.Number`.
- Ensures only numeric types can be stored in the `Box`.
- Provides `getValue()` and `setValue()` methods to access and modify the value.
2. `Main.java`:
- Demonstrates a valid instantiation with `Box<Integer>`.
- Commented example `Box<String>` shows compile-time restriction (invalid type).
WHY:
- Enforcing bounds (`T extends Number`) ensures that only valid numeric types are allowed.
- Prevents misuse of the class with incompatible data types.
- Improves type safety and readability by making constraints explicit.
REAL-WORLD APPLICATIONS:
- Bounded generics are useful in mathematical utility classes, statistical libraries,
or any domain where only numeric data makes sense.
- For example, implementing a generic `Calculator<T extends Number>` or `Statistics<T extends Number>`.
NOTES:
- `Box<Integer>`, `Box<Double>`, and `Box<Float>` work correctly.
- `Box<String>` fails at compile-time, avoiding runtime errors.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 37f4d04 commit 9a63eb1
2 files changed
+50
-0
lines changedLines changed: 13 additions & 0 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
| 1 | + | |
| 2 | + | |
| 3 | + | |
| 4 | + | |
| 5 | + | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
| 12 | + | |
| 13 | + | |
Lines changed: 37 additions & 0 deletions
| 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 | + | |
0 commit comments