Bounded Type Parameters in Generic Methods
You'll learn how to restrict type parameters in method signatures independent of the class they appear in, giving those methods their own type constraints.
The Core Idea
Just as classes can declare bounded type parameters (like <T extends Number>), individual methods can declare their own bounded type parameters—completely separate from any class-level generics. This lets you write utility methods with specific type requirements without forcing constraints on the entire class.
The method-level type parameter appears before the return type in the signature:
public static <T extends Comparable<T>> T findMax(T a, T b) {
return a.compareTo(b) > 0 ? a : b;
}
Here, <T extends Comparable<T>> declares that this method works only with types that implement Comparable. The class containing this method doesn't need to be generic at all.
Method-Level vs Class-Level Bounds
These are independent scopes:
public class Container<T> { // T at class level (unbounded)
// Method declares its own bounded U
public <U extends Number> void processNumber(U value) {
double d = value.doubleValue(); // Can call Number methods
System.out.println(d);
}
}
The method's U has no relationship to the class's T. You can even shadow (reuse) the same letter, though it's confusing.
Why This Matters
Method-level bounds let you write flexible utility methods in non-generic classes or apply different constraints than the containing class uses. It's perfect for static helper methods:
public static <T extends AutoCloseable> void safeClose(T resource) {
resource.close(); // Bound guarantees close() exists
}
Key Takeaway:
Bounded type parameters in generic methods provide compile-time type safety at the method level, independent of any class-level generics, enabling precise control over what types a method accepts.