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

Bounded Type Parameters with Interfaces

Using interfaces as upper bounds to ensure type parameters implement specific contracts.

Bounded Type Parameters with Interfaces

What You'll Learn

You'll learn how to use interfaces as upper bounds in generics to guarantee that type parameters implement specific behaviors.

The Core Idea

Just as you can bound a type parameter to a class (like <T extends Number>), you can also bound it to an interface. This ensures that any type argument must implement that interface's contract. The syntax is identical: use extends (not implements) even when bounding to an interface.

This is powerful because it lets your generic code call methods defined in the interface, knowing with certainty that the type parameter supports them.

How It Works

// Bound to Comparable interface
public class Sorter<T extends Comparable<T>> {
    private T first;
    private T second;

    public Sorter(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T getSmaller() {
        // Safe: T MUST implement Comparable
        return first.compareTo(second) < 0 ? first : second;
    }
}

Now you can only create a Sorter with types that implement Comparable:

Sorter<String> s1 = new Sorter<>("apple", "banana"); // ✓ String implements Comparable
Sorter<Integer> s2 = new Sorter<>(5, 10);            // ✓ Integer implements Comparable

// Without the bound, calling compareTo() would be impossible

Why This Matters

Without the bound, the compiler treats T as Object, which doesn't have a compareTo() method. The interface bound gives you access to the interface's full API within your generic class.

Key Takeaway: Use <T extends InterfaceName> to restrict type parameters to types implementing specific interfaces, enabling you to call those interface methods safely within your generic code.