Accessing Members from All Bounds
You'll learn how a type parameter with multiple bounds gives you access to all the methods and fields from every bound you specify.
When you declare a type parameter with multiple bounds, the compiler treats that type parameter as if it implements or extends all of those bounds simultaneously. This means inside your generic code, you can safely call any method or access any field that belongs to any of the bounds.
The Core Idea
Think of multiple bounds as a contract: "Whatever type is provided must fulfill all these requirements." Once that contract is established, you're guaranteed that all methods from all bounds are available.
If you declare <T extends Number & Comparable<T>>, the compiler knows that T is both a Number and Comparable<T>. Inside your generic method or class, you can call T's doubleValue() (from Number) and compareTo() (from Comparable) on the same object.
Example Illustration
public class Calculator {
public static <T extends Number & Comparable<T>> T max(T a, T b) {
// Access Comparable's method
int comparison = a.compareTo(b);
// Access Number's method
double aValue = a.doubleValue();
// Use both bounds' capabilities
return comparison >= 0 ? a : b;
}
}
Here, T must satisfy both bounds, so you can freely use members from Number (doubleValue()) and from Comparable<T> (compareTo()). The compiler guarantees both are present.
Why This Matters
Without multiple bounds, you'd be limited to methods from just one type. Multiple bounds unlock the full API surface of all specified types, enabling richer, more expressive generic code.
Key Takeaway: When a type parameter has multiple bounds, all methods and fields from every bound are accessible within your generic code—the type parameter becomes a composite of all its bounds.