Commit 444e45f
committed
feat(generic-methods): add example of generic method with type parameter <T>
WHAT:
- Implemented `Test4` class showcasing a static generic method `genericDisplay(T element)`.
- Method prints both the runtime class type and the value of the passed argument.
- Demonstrated usage with `Integer`, `String`, and `Double` inputs.
WHY:
- Highlights how **generic methods** differ from generic classes/interfaces.
- Shows type inference in action — no explicit type declaration is needed at the call site.
- Reinforces the concept of compile-time type safety with generics while maintaining runtime flexibility.
HOW (Logic Flow):
1. Define a generic method `static <T> void genericDisplay(T element)`.
2. Use `element.getClass().getName()` to print the runtime type of the object.
3. Invoke method with different types (`Integer`, `String`, `Double`) without casting.
BENEFITS:
- Avoids method overloading for different data types.
- Promotes **code reusability** and **type safety** in utility methods.
- Enables compile-time checks while working seamlessly across multiple types.
REAL-WORLD APPLICATIONS:
- Utility libraries (e.g., logging frameworks, data serializers) where methods need to handle arbitrary object types.
- Collection processing (printing, transformation, or validation of heterogeneous data).
- Framework design (e.g., Spring, Hibernate) where methods often use generics for maximum flexibility.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 8b93867 commit 444e45f
File tree
1 file changed
+11
-10
lines changed- Section24JavaGenerics/src/GenericMethods
1 file changed
+11
-10
lines changedLines changed: 11 additions & 10 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
3 | | - | |
| 1 | + | |
4 | 2 | | |
5 | | - | |
6 | | - | |
| 3 | + | |
7 | 4 | | |
8 | | - | |
9 | | - | |
| 5 | + | |
10 | 6 | | |
11 | 7 | | |
12 | 8 | | |
13 | | - | |
14 | | - | |
| 9 | + | |
15 | 10 | | |
16 | 11 | | |
17 | 12 | | |
| |||
20 | 15 | | |
21 | 16 | | |
22 | 17 | | |
23 | | - | |
| 18 | + | |
| 19 | + | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
0 commit comments