Commit b63859a
committed
feat(generics-upper-bounds): add example of upper-bounded wildcards with Animal hierarchy
WHAT:
- Introduced `Animal` base class with subclasses `Dog` and `Cat`, each overriding `sound()`.
- Implemented method `makeSound(List<? extends Animal>)` that accepts a list of any subclass of `Animal`.
- Demonstrated runtime polymorphism by passing `List<Dog>` and `List<Cat>` to the method.
WHY:
- Showcases how upper-bounded wildcards (`? extends Animal`) allow methods to operate on collections of a type and its subtypes.
- Useful for read-only scenarios where elements are consumed but not safely added (PECS principle: Producer Extends).
- Demonstrates real-world applicability: handling heterogeneous animal types with one generic method.
DETAILS:
- `List<? extends Animal>` ensures flexibility to accept both `List<Dog>` and `List<Cat>`.
- Iteration treats elements as `Animal` → enabling polymorphic method calls like `animal.sound()`.
- Prevents unsafe additions (cannot add a `Dog` to `List<? extends Animal>` safely, except `null`).
BENEFITS:
- Promotes reusable and type-safe code when processing different subclasses in collections.
- Demonstrates dynamic method dispatch via generics and wildcards.
- Reinforces understanding of covariance in generics (`? extends T`).
REFERENCE:
- PECS Principle:
- Producer → `? extends T` (safe for reading).
- Consumer → `? super T` (safe for writing).
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent bb7ffe9 commit b63859a
File tree
1 file changed
+66
-0
lines changed- Section24JavaGenerics/src/UpperBoundedWildcards
1 file changed
+66
-0
lines changedLines changed: 66 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 | + | |
| 62 | + | |
| 63 | + | |
| 64 | + | |
| 65 | + | |
| 66 | + | |
0 commit comments