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

Syntax: Combining extends with &

Learn the syntax <T extends ClassType & Interface1 & Interface2> for declaring multiple bounds.

Syntax: Combining extends with &

What you'll learn: How to declare a generic type parameter that must satisfy multiple type requirements simultaneously.

The Core Syntax

When you need a type parameter to extend both a class (or interface) and one or more interfaces, Java provides the & operator to combine these bounds:

<T extends ClassType & Interface1 & Interface2>

This syntax tells the compiler: "Type T must be a subtype of ClassType AND implement Interface1 AND implement Interface2."

Structure and Rules

The syntax follows strict ordering:

  1. Class first (if present): If you're bounding by a class, it must come first
  2. Interfaces after: Follow with interfaces, separated by &
  3. No class required: You can bound by interfaces only: <T extends Interface1 & Interface2>

Example Declaration

public class DataProcessor<T extends Number & Comparable<T>> {
    private T value;
    
    public DataProcessor(T value) {
        this.value = value;
    }
    
    public boolean isGreaterThan(T other) {
        return value.compareTo(other) > 0;  // Comparable method
    }
    
    public double toDouble() {
        return value.doubleValue();  // Number method
    }
}

Here, T must extend Number (giving access to doubleValue()) and implement Comparable<T> (giving access to compareTo()). Both constraints are enforced at compile time.

Why This Matters

Multiple bounds let you require several capabilities from a type parameter, ensuring you can safely call methods from all specified types within your generic class or method.

Key Takeaway: Use <T extends Type1 & Type2 & Type3> to require a type parameter to satisfy multiple bounds, with any class bound appearing first, followed by interfaces separated by &.