Lesson 5 of 718 minModule progress 0%

Module 12: Generics and Type Safety

Wildcards: extends, super, and PECS

Understand ? extends and ? super with simple producer and consumer rules.

Author

Java Learner Editorial Team

Reviewer

Technical review by Java Learner

Last reviewed

2026-04-17

Java version

Java 25 LTS

How this lesson was prepared: AI-assisted draft, manually edited for clarity, and checked against current Java documentation and runnable examples.

Learning goals

  • Understand `? extends` and `? super`
  • Use PECS in a practical way
  • Know when a wildcard helps more than an exact type

Wildcards add flexibility at the use site: Sometimes the method should accept “a list of this type or a subtype” instead of one exact generic type.

PECS is the practical shortcut: Producer extends, consumer super. If you mainly read from it, extends often fits. If you mainly write into it, super often fits.

Do not turn every signature into wildcard soup: Use wildcards when they improve real flexibility, not when they make the API harder to understand.

Readability still matters: A precise simpler signature is often better than a maximally flexible confusing one.

Runnable examples

Read numbers from any numeric subtype list

public static double sum(java.util.List<? extends Number> numbers) {
    double total = 0;
    for (Number number : numbers) {
        total += number.doubleValue();
    }
    return total;
}

Expected output

The method can accept `List<Integer>`, `List<Double>`, and other numeric subtype lists.

Mini exercise

Explain whether `? extends Number` is better for reading from a list or writing into it.

Summary

  • Wildcards make APIs flexible at the use site.
  • PECS is a practical rule for deciding between `extends` and `super`.
  • Use wildcards for clarity and flexibility, not as decoration.

Next step

Finish the module by understanding type erasure and by using generics in one mini-project.

Sources used

Advertisement

Lesson check

What does PECS stand for?

Next lesson →