Reputation: 851
I was trying out some Generics and noticed this.
class D extends C {}
class C extends B {}
class B extends A {}
class A {}
class Z<E extends B> {}
class temp {
public static void main(String[] args) {
Z z1 = new Z();
Z<B> z2 = new Z<B>();
Z<C> z3 = new Z<C>();
Z<D> z4 = new Z<D>();
Z<A> z5 = new Z<A>(); //compile error - E can be subsituted only until B
Z<? extends A> z5 = null; //no compile error
}
}
Why doesn't this throw a compile error?
Z<? extends A> z5 = null;
The class Z has a upper bound until B, and yet I can have a wildcard declaration that extends until A. Ofcourse I can't instantiate it to
Z<? extends A> z5 = new Z<A>(); //Not allowed
but shouldn't this have been a compile error? Why does it allow this declaration?
EDIT: Corrected the instantiation of z5
Upvotes: 3
Views: 107
Reputation: 200138
I think one way of looking at what you are asking is, should Java allow you to write
Z<?> z;
More generally, should Java allow any generic type to be used with an unbounded wildcard. If you think the answer is "yes", and I do think that, then you have got your answer.
Upvotes: 3