Java Reference
In-Depth Information
Understanding Polymorphism and Generics
Be careful when you work with polymorphism and generic types that do not use the
extends keyword. There is no implied upper bound when a specifi c generic type is
declared without the extends keyword. To demonstrate, let's use the Cupboard class from
earlier in this section that used a formal type parameter:
public class Cupboard<T> {
//definition of class
}
The following statement is valid because we are assigning a Cupboard<Number> object to
a Cupboard<Number> reference:
Cupboard<Number> a = new Cupboard<Number>(123);
Now consider the following statement that assigns a Cupboard<Double> object to a
Cupboard<Number> reference. Is it valid?
Cupboard<Number> b = new Cupboard<Double>(456.0);
Surprisingly, the answer is no: the previous statement does not compile and generates
the following compiler error:
SubtypeDemo.java:5: incompatible types
found : Cupboard<java.lang.Double>
required: Cupboard<java.lang.Number>
Cupboard<Number> b = new Cupboard<Double>(456.0);
^
Even though a Double is a Number , a Cupboard<Double> is not a Cupboard<Number> . If you
want to use a polymorphic reference, you need to use an upper bound. For example, the
following statement is valid:
Cupboard<? extends Number> c = new Cupboard<Double>(789.0);
The ? is referred to as a wildcard and creates a reference that can point to any
Cupboard<?> object where ? extends the Number class. The previous statement is valid
because we are assigning a Cupboard<Double> object to a Cupboard<? extends Number>
reference and Double extends Number .
We use the extends keyword to create an upper-bound generic type. In the next section
I discuss how to use the super keyword together with a wildcard to create a lower-bound
generic type, together with the other details that you need to know about using generic
wildcards.
Search WWH ::




Custom Search