Bounded type parameters are a powerful feature in Java generics that allow you to restrict the types that can be used as type arguments in a parameterized type. This concept enhances type safety and provides more flexibility when working with generic classes and methods.
In Java, you can use bounded type parameters to specify that a generic type must be a subtype of a particular class or implement certain interfaces. This is achieved using the extends
keyword for upper bounds and the super
keyword for lower bounds.
Upper bounds restrict a type parameter to be a subtype of a specific type. The syntax is:
<T extends UpperBoundType>
Here's an example of a method using an upper bounded type parameter:
public static <T extends Number> double sum(T[] array) {
double total = 0;
for (T element : array) {
total += element.doubleValue();
}
return total;
}
In this example, T
is restricted to be a subtype of Number
, allowing the method to work with any numeric type.
Lower bounds specify that a type parameter must be a supertype of a particular type. The syntax is:
<T super LowerBoundType>
Here's an example demonstrating a lower bounded type parameter:
public static void addNumbers(List<? super Integer> list) {
for (int i = 1; i <= 5; i++) {
list.add(i);
}
}
This method can accept a List
of Integer
or any supertype of Integer
, such as Number
or Object
.
Java also supports specifying multiple bounds for a type parameter. This is useful when you need a type to satisfy multiple conditions:
<T extends ClassA & InterfaceB & InterfaceC>
In this case, T
must be a subtype of ClassA
and implement both InterfaceB
and InterfaceC
.
Bounded type parameters are closely related to other generic concepts in Java. To deepen your understanding, explore Java Generic Methods and Java Generic Classes.
Bounded type parameters are a crucial feature in Java generics, offering a balance between flexibility and type safety. By mastering this concept, you can write more robust and reusable code that leverages the full power of Java's type system.