Commit 29e28a5
committed
feat(generic-methods): demonstrate method overloading with generics and specific types
WHAT:
- Added `MethodOverloading` class to explore how **generic methods** interact with **method overloading**.
- Used `printArray(T[])` from `Test` class (via static import) to print arrays of different types (`Integer[]`, `String[]`).
- Implemented two `display` methods:
1. A generic version `<T> void display(T element)`.
2. A type-specific version `void display(Integer element)`.
WHY:
- Shows how **Java resolves overloaded methods** when both a generic and a specific method exist.
- Emphasizes that the **most specific method** (non-generic) is chosen by the compiler when applicable.
HOW (Logic Flow):
1. Call `printArray()` for integers and strings, proving reusability of a single generic method.
2. Call `display(12)` → matches the `Integer`-specific method.
3. Call `display(12.1)` → no exact match, so compiler falls back to the generic version.
OUTPUT BEHAVIOR:
- `printArray(intArray)` → prints integer elements.
- `printArray(stringsArray)` → prints string elements.
- `display(12)` → "Integer Display: 12"
- `display(12.1)` → "Generic display: 12.1"
BENEFITS:
- Demonstrates **method resolution precedence** between generics and overloaded methods.
- Reinforces the flexibility of generic methods without losing the optimization of type-specific overloads.
- Shows practical use cases of mixing polymorphism + generics.
REAL-WORLD APPLICATIONS:
- API design: providing both generic fallbacks and optimized type-specific implementations.
- Framework utilities: e.g., `Collections.sort()` has generic forms, but some libraries offer specialized overloads for performance.
- Logging/debugging frameworks where generic loggers coexist with specialized ones for primitives or common types.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent 444e45f commit 29e28a5
File tree
1 file changed
+61
-0
lines changed- Section24JavaGenerics/src/GenericMethods
1 file changed
+61
-0
lines changedLines changed: 61 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 | + | |
| 38 | + | |
| 39 | + | |
| 40 | + | |
| 41 | + | |
| 42 | + | |
| 43 | + | |
| 44 | + | |
| 45 | + | |
| 46 | + | |
| 47 | + | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
0 commit comments