Bounded Type Parameters with Classes
What you'll learn: How to restrict generic type parameters to specific classes and their subclasses using concrete class bounds.
The Core Idea
Sometimes your generic class needs to work only with types that extend a particular class. By specifying a concrete class as an upper bound, you restrict what types can be used—and gain access to that class's methods and fields inside your generic code.
You've already seen the extends keyword with bounded type parameters. Now we're applying it with concrete classes (not just interfaces or Object).
Syntax and Example
public class Box<T extends Number> {
private T value;
public Box(T value) {
this.value = value;
}
public double getDoubleValue() {
// Safe! T is guaranteed to be a Number or subclass
return value.doubleValue();
}
}
Now you can create boxes of any Number subclass:
Box<Integer> intBox = new Box<>(42);
Box<Double> doubleBox = new Box<>(3.14);
System.out.println(intBox.getDoubleValue()); // 42.0
System.out.println(doubleBox.getDoubleValue()); // 3.14
But you cannot do this:
Box<String> stringBox = new Box<>("text"); // Compile error!
// String does not extend Number
Why This Matters
Bounding to a class gives you two benefits:
- Type safety – only appropriate types can be used
- Access to class methods – you can call
Numbermethods likedoubleValue()inside your generic class
Key Takeaway: Bounded type parameters with concrete classes restrict T to a specific class hierarchy, enabling safe access to that class's methods within your generic implementation.