Course contentsShow
← Java
Lesson 911 of 2,87022. Generics: Bounds and WildcardsFree lesson

The extends Keyword in Generic Type Parameters

Using extends to specify an upper bound for a type parameter, restricting it to a specific class or its subclasses.

The extends Keyword in Generic Type Parameters

What you'll learn: How to restrict a generic type parameter to accept only a specific class or its subclasses using the extends keyword.


What Does extends Do in Generics?

When you declare a generic type parameter, you can use the extends keyword to set an upper bound—a constraint that limits which types are allowed. This tells the compiler: "This type parameter can only be filled by this class or any class that inherits from it."

The syntax looks like this:

class MyClass<T extends SomeClass>

This means T must be SomeClass or one of its subclasses.

Why Use Upper Bounds?

Without bounds, a type parameter defaults to Object, meaning you can't call any specific methods on it. By specifying an upper bound, you gain access to all methods from that bound class.

class NumberBox<T extends Number> {
    private T value;
    
    public NumberBox(T value) {
        this.value = value;
    }
    
    public double getDoubleValue() {
        return value.doubleValue(); // Safe! Number has this method
    }
}

Now you can create NumberBox<Integer> or NumberBox<Double>, but not NumberBox<String> because String doesn't extend Number.

Think of It Like a Filter

Imagine a box that only accepts "sports equipment." You can put a basketball or tennis racket inside, but not a book. The extends keyword works the same way—it filters which types are acceptable.

NumberBox<Integer> intBox = new NumberBox<>(42);
NumberBox<Double> doubleBox = new NumberBox<>(3.14);
// NumberBox<String> stringBox = new NumberBox<>("text"); // Compiler error!

Key Takeaway:
Use <T extends ClassName> to restrict a type parameter to a specific class and its subclasses, gaining compile-time safety and access to that class's methods.