Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generics behavior for bounded wildcards

Tags:

java

generics

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

like image 768
The_301 Avatar asked Mar 24 '26 12:03

The_301


1 Answers

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.

like image 52
Marko Topolnik Avatar answered Mar 27 '26 02:03

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!