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

Accessing Members from All Bounds

Understand that methods and fields from all bounds are accessible on the type parameter within the generic code.

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.