Accessing Members Through Bounded Type Parameters
What you'll learn: How bounded type parameters let you safely call methods and access fields that are guaranteed to exist because of the upper bound.
When you declare a generic type parameter with an upper bound using extends, you're not just restricting what types can be used—you're also gaining access to all the methods and fields defined by that bound. This is the key benefit: the compiler knows your type parameter is at least that bound, so it lets you call any public members from it.
Why This Matters
Without bounds, a plain <T> is treated as Object due to type erasure. You can only call Object methods like toString() or equals(). But with <T extends Number>, the compiler knows your T is a Number, so you can call Number methods like doubleValue() or intValue().
The Mechanism
public class Calculator<T extends Number> {
private T value;
public Calculator(T value) {
this.value = value;
}
public double getDoubleValue() {
// Because T extends Number, we can call Number's methods
return value.doubleValue();
}
public int getIntValue() {
return value.intValue();
}
}
The bound acts as a contract. The compiler sees T extends Number and permits any method call that Number guarantees. Without the bound, value.doubleValue() would be a compile error—the compiler wouldn't know if T has that method.
With Interfaces
public class Container<T extends Comparable<T>> {
private T item;
public boolean isGreaterThan(T other) {
// We can call compareTo because T extends Comparable
return item.compareTo(other) > 0;
}
}
Key Takeaway: Bounded type parameters grant access to all public methods and fields of the bound type, enabling type-safe operations beyond basic Object methods.