Please help me with this:
If Lion IS-A Animal
and given Cage<T>
:
Cage<? extends Animal> c = new Cage<Lion>(); // ok,
but
Set<Cage<? extends Animal>> cc = new HashSet<Cage<Lion>>(); // not ok
What I don't see here?
A bounded wildcard is one with either an upper or a lower inheritance constraint. The bound of a wildcard can be either a class type, interface type, array type, or type variable. Upper bounds are expressed using the extends keyword and lower bounds using the super keyword.
To declare an upper-bounded wildcard, use the wildcard character ('? '), followed by the extends keyword, followed by its upper bound.
Wildcards are nothing but the question mark(?) that you use in the Java Generics. We can use the Java Wildcard as a local variable, parameter, field or as a return type. But, when the generic class is instantiated or when a generic method is called, we can't use wildcards.
If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
When assigning to a variable (Set<T>
) with a non-wildcard generic type T
, the object being assigned must have exactly T
as its generic type (including all generic type parameters of T
, wildcard and non-wildcard). In your case T
is Cage<Lion>
, which is not the same type as Cage<? extends Animal>
.
What you can do, because Cage<Lion>
is assignable to Cage<? extends Animal>
, is use the wildcard type:
Set<? extends Cage<? extends Animal>> a = new Set<Cage<Lion>>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With