Skip to content

Commit 8f1e66c

Browse files
authored
Update covariance-contravariance.md
1 parent 508d095 commit 8f1e66c

1 file changed

Lines changed: 57 additions & 0 deletions

File tree

generics/covariance-contravariance.md

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,3 +16,60 @@
1616
| **PECS Mnemonic** | **P**roducer **E**xtends | **C**onsumer **S**uper |
1717
| **Primary Use Case** | When you are **reading** items *from* a generic structure (it *produces* items for you). | When you are **writing** items *to* a generic structure (it *consumes* items from you). |
1818

19+
20+
21+
## Wildcards with upper bounds
22+
23+
This example shows using wildcard types with upper bounds to accept lists of
24+
subclasses.
25+
26+
```java
27+
abstract class Shape {
28+
29+
abstract void draw();
30+
}
31+
32+
class Rectangle extends Shape {
33+
34+
@Override
35+
void draw() {
36+
IO.println("Drawing rectangle");
37+
}
38+
}
39+
40+
class Circle extends Shape {
41+
42+
@Override
43+
void draw() {
44+
IO.println("Drawing circle");
45+
}
46+
}
47+
48+
// Generic wildcard example
49+
void main() {
50+
51+
List<Rectangle> shapes1 = new ArrayList<>();
52+
shapes1.add(new Rectangle());
53+
54+
List<Circle> shapes2 = new ArrayList<>();
55+
shapes2.add(new Circle());
56+
shapes2.add(new Circle());
57+
58+
drawShapes(shapes1);
59+
drawShapes(shapes2);
60+
}
61+
62+
void drawShapes(List<? extends Shape> lists) {
63+
64+
for (Shape s : lists) {
65+
s.draw();
66+
}
67+
}
68+
```
69+
70+
The `drawShapes` method uses a bounded wildcard `? extends Shape` to accept
71+
lists of any type that extends `Shape`. This demonstrates covariance - the
72+
method can accept `List<Rectangle>`, `List<Circle>`, or `List<Shape>`. The
73+
wildcard makes the method more flexible than `List<Shape>` alone, which would
74+
not accept lists of subtypes. This is useful for read-only operations where
75+
you need to process elements polymorphically without adding new elements.

0 commit comments

Comments
 (0)