Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the use of Collection<? extends SomeAbstractClass> instead of Collection<SomeAbstractClass>

Tags:

java

generics

So lets say we have an Java Application with an abstract class named SomeAbstractClass and at least 10 subclasses of this super class.

Whats the use of using this abstract super class in generics in the way Collection<? extends SomeAbstractClass> instead of just using Collection<SomeAbstractClass>

Maybe I missed something very fundamental stuff inside generics.

like image 751
cpasemann Avatar asked Oct 21 '22 22:10

cpasemann


1 Answers

The difference between these two declarations:

Collection<? extends A> c1;
Collection<A> c2;

Is that c2 can hold instances of A or any subclass, but c1 can hold instances of some unknown but particular subclass of A (or A) or any of the unknown class's subclasses.

You can't add items to c2 because the compiler doesn't know what type it is, only that if you get one out it can be cast to A.

Further, you can not assign (ie cast) c1 to c2 - c1 is not a subclass of c2's type.

like image 187
Bohemian Avatar answered Oct 28 '22 20:10

Bohemian