... List<Number>
would also work on a List<Integer>
. Consider the fact that you can add a Double
object to a List<Number>
because a Double
is a Number
, but you cannot add a Double
object to a List<Integer>
because a Double
is not an Integer
. Thus, the subtype relationship does not hold.
How do we create a more flexible version of method sum
that can total the elements of any List
containing elements of any subclass of Number
? This is where wildcard type arguments are important. Wildcards enable you to specify method parameters, return values, variables or fields, and so on, that act as supertypes or subtypes of parameterized types. In Fig. 20.11, method sum
’s parameter is declared in line 52 with the type:
List<? extends Number>
A wildcard type argument ...
Get Java How to Program, Early Objects, 11th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.