What Are Bounded Type Parameters?
You'll learn why sometimes you need to restrict what types can be used with generics, and when simple unbounded type parameters like <T> aren't enough.
The Limitation of Unbounded Generics
When you declare a generic class or method with <T>, you're saying "T can be any type." This is powerful, but sometimes too flexible. Inside your generic code, you can only use methods available on Object (like toString() or equals()), because Java doesn't know what T actually is.
The problem: What if you need to perform operations that require specific methods? For example, what if you want to compare elements using compareTo(), or perform mathematical operations?
When Unbounded Parameters Fall Short
Imagine building a generic method to find the maximum of two values:
public static <T> T max(T a, T b) {
// How do we compare a and b?
// We can't call a.compareTo(b) because T might not have that method!
}
With an unbounded <T>, you're stuck. You can't assume T has a compareTo() method because T could be literally anything—String, Integer, or even a custom class with no comparison logic.
The Solution Preview
This is where bounded type parameters come in. They let you say: "T can be any type, but only if it meets certain requirements." You restrict the allowed types to those that extend a specific class or implement specific interfaces, giving you access to their methods inside your generic code.
Key Takeaway: Bounded type parameters solve the problem of needing specific operations inside generic code by restricting type arguments to those that provide the required functionality—you get both flexibility and compile-time type safety.