|
Wildcards in Parameterized Classes/Interfaces
in Java |
|
Prof. David Bernstein
|
| Computer Science Department |
| bernstdh@jmu.edu |
Object (since it is an ancestor of
all classes) but this isn't "type safe"Object
is appropriate
extends, followed by, what are
unfortunately called, the bounding types (separated by
an &)extends was probably a bad choice
since any class that either extends the bounding type or
implements the bounding type can be used (which is why
there can be more than one)
? extends Type
? super Type
Object
(if unbounded)
Statistics class that can,
among other things, find the maximum and minimum
of a data setOrdered interface to characterize
the datamin() and max() methods that
are passed
List<Ordered> objects
Ordered Interface
Statistics Class
max() that is passed
a List of objects that
implements Ordered
(e.g., List<Person> where
Person implements Ordered)
will not compile because the List class must
ensure that its elements are Person objects,
not Ordered objects (a type of class
invariance)
? represents an unknown type? extends B
where
B, the upper bound, can be a class or interface
(and "extends" means "extends or implements")
Object
(the root node) at the top and descendants at lower
levels
Statistics Class
compareTo() method is not type safe
because it only ensures that this and
other are both Ordered
(but not necessarily of the same type)Ordered
max() and min() methods can
now return an object of appropriate type
Ordered Interface
Statistics Class
Rectangle classShape interface that is realized by the
Rectangle classList<Rectangle>
Rectangle class, it may only need
the capabilities of the Shape
interfaceList<Shape>
List<? extends Shape>
? super B
where
B is the lower bound
Object
(the root node) at the top and descendants at lower
levels
T
(i.e., the method gets objects from the collection) then
it can be of type <? extends T>
(because it can produce more specialized objects)T
(i.e., the method adds objects to the collection) then
it can be of type <? super T>
(because it can consume more generalized objects)