Generics
Bounded Type Parameters
Analyze bounded type parameters, single upper bounds, and multiple intersection bounds.
Interview: Focuses on upper bounds, multiple bounds syntax rules (class first, then interfaces), and compiler validation.
Bounded Type Parameters restrict the types that can be used as arguments in parameterized types. By declaring upper bounds, you limit parameters to a specific class or its subclasses, enabling access to methods defined in the bounds.
Upper Bounds
Declared using the extends keyword: <T extends Number>. Restricts arguments to the specified class or its subclasses.
Multiple Bounds
Combines bounds using the ampersand operator: <T extends Class & Interface>. Restricts arguments to types that satisfy all bounds.
Method Access
Allows calling methods defined in the bounded types (e.g. doubleValue()) on generic objects without explicit casting.
Multiple Intersection Bounds Syntax
When declaring multiple bounds, the compiler enforces strict ordering:
- Class First: If one of the bounds is a class, it must be declared first in the list:
<T extends Class & Interface1 & Interface2>. - Single Class Limit: A type parameter can declare at most one class bound, as Java does not support multiple inheritance of classes.
Common Pitfalls
- Declaring interfaces before classes: Writing
<T extends Comparable & Number>, which causes a compile-time error. - Declaring multiple class bounds: Writing
<T extends Number & Thread>, which violates Java's single inheritance rule.
Best Practices
- Use bounds to access methods: Apply bounds when you need to access specific methods on generic objects (e.g. comparing elements).
- Keep intersections simple: Limit multiple bounds to one class and one interface to keep code readable.
Interview-Relevant Information
Q1: What is the syntax rule for declaring multiple bounds?
Answer: If one of the bounds is a class, it must be declared first, followed by any interfaces separated by ampersands: <T extends ClassBound & InterfaceBound1 & InterfaceBound2>.
Q2: Why does the compiler require class bounds to be declared first?
Answer: It simplifies how the compiler generates bytecode. During type erasure, the type parameter is replaced by its first bound, which must be the class bound to ensure correct method dispatch.
Quick Checklist
Can you write a bounded type parameter declaration, explain why classes must be listed first in multiple bounds, and state how many class bounds are allowed? If yes, you understand bounded type parameters.
Use Cases
Building mathematical processors that operate on Number types.
Implementing sorting utilities that require elements to implement Comparable.
Common Mistakes
Declaring interface bounds before class bounds in multiple bounds list.
Attempting to declare multiple class inheritance bounds.