What Are Multiple Bounds in Generics?
You'll learn how to constrain a generic type parameter to satisfy multiple requirements simultaneously using Java's & syntax.
The Core Idea
Sometimes you need a type parameter that meets more than one constraint. For example, you might want a type that's both Comparable (so you can sort it) and Serializable (so you can save it to disk). Java lets you specify multiple bounds on a single type parameter using the & operator.
Multiple Bounds Syntax
When declaring a type parameter, you can require it to extend one class and/or multiple interfaces by separating them with &:
<T extends FirstBound & SecondBound & ThirdBound>
Important rules:
- If one bound is a class, it must come first
- All other bounds must be interfaces
- You can only specify one class (Java's single inheritance), but multiple interfaces
Example in Action
public class DataProcessor<T extends Comparable<T> & Serializable> {
private T data;
public DataProcessor(T data) {
this.data = data;
}
// We can call compareTo because T extends Comparable
public boolean isGreaterThan(T other) {
return data.compareTo(other) > 0;
}
// We know T is Serializable, so serialization is safe
}
Here, T must be both Comparable<T> (allowing comparisons) and Serializable (allowing object persistence). Types like String and Integer satisfy both constraints.
The Restaurant Analogy
Think of it like hiring someone who must be both a certified chef and a licensed driver—they need to meet multiple qualifications to get the job.
Key Takeaway: Multiple bounds let you specify that a type parameter must satisfy several constraints simultaneously using <T extends Bound1 & Bound2>, with at most one class bound (first) and any number of interface bounds.