Lesson 4 of 718 minModule progress 0%

Module 12: Generics and Type Safety

Bounded Type Parameters

Use bounds to say what a type must support without giving up flexibility.

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

  • Use upper bounds with `extends`
  • See why bounds enable more useful generic code
  • Avoid over-constraining generic APIs

A bound limits what types are allowed: <T extends Number> means the generic code only accepts numeric types or subclasses.

Bounds make operations possible: If the generic code needs doubleValue() or another shared capability, a bound tells the compiler that the method exists.

Do not add bounds just because you can: Restrict the API only when the code really depends on that capability.

Design goal: Keep the API as open as possible, but no more open than is actually safe.

Runnable examples

A method restricted to numeric values

public static <T extends Number> double twice(T value) {
    return value.doubleValue() * 2;
}

System.out.println(twice(4));

Expected output

8.0

Mini exercise

Write a generic method that accepts `T extends Number` and returns the value plus one as a double.

Summary

  • Bounds restrict generic APIs when needed.
  • They allow access to shared behavior safely.
  • A good generic API stays open until there is a reason to narrow it.

Next step

Next, use wildcards to make APIs more flexible at call sites.

Sources used

Advertisement

Lesson check

Why use a bounded type parameter?

Next lesson →