In Java generics, the concept of
upper bounded wildcards introduces a flexible way of dealing with collections of objects that belong to a specific family of types. Imagine you have a method that is intended to process a collection of numbers. You might naturally think of using the
Number
class since classes like
Integer
,
Double
, and
Float
are all under this umbrella. However, without upper bounded wildcards, your method would be restricted and wouldn't accept a list of any subtype of
Number
.
Upper bounded wildcards are defined using the keyword
extends
. So, if you have a type parameter
A
and a subtype
B
, you could use the wildcard
List<? extends A>
to allow the method to accept arguments of
List<B>
. An example method that sums a list of any kind of numbers is as follows:
public static double sumOfList(List<? extends Number> list) { double sum = 0.0; for (Number num : list) { sum += num.doubleValue(); } return sum;}
This method illustrates the use of an upper bounded wildcard by accepting a list of any class that is a subtype of
Number
, hence showcasing the flexibility that generics add to Java programming while still maintaining type safety.