Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics in Java

Tags:

java

generics

I came across something peculiar today. Take a look at this code snippet:

List <Rectangle> test1 = new LinkedList<Rectangle>();
List <Shape> test2 = test1; //Compiler Error;

This is of course is assuming that class Rectangle is a subclass of Shape. Can someone explain to me why this is an error?

like image 875
Sarindipity Avatar asked May 14 '26 07:05

Sarindipity


2 Answers

You need to use wild card. Like this:

List<Rectangle> test1 = new LinkedList<Rectangle>();
List<? extends Shape> test2 = test1;

As Rectangle extends Shape.

The reason for this is that if test2 is just List<Shape>, you will expect test2.add(..) to accept any shape but that is not the case if you allows test1 (which is List<Rectangle>), test1 will not accept any shape that is not Rectangle.

Hope this helps.

like image 196
NawaMan Avatar answered May 15 '26 21:05

NawaMan


If this code worked, you could continue by inserting into test2 a Circle -- thus utterly breaking the guarantee that test1 makes, that only Rectangles will ever be inserted in it.

The general principle (language independent -- a matter of logic -- even though counter-intuitive): a bag of bananas is NOT a bag of fruit... in a world of mutable objects (the functional programming world, where every object is immutable once created, is MUCH simpler!). That's because you can add an apple to a bag of fruit (since an apple is a piece of fruit), but you can't add an apple to a bag of bananas (since an apple is not a banana).

BTW, this is very similar to the reason a square is not a rectangle (again, in a world of mutable objects): because given a (mutable) rectangle you can mutate the two sides independently, but, given a square, you can't. (In geometry, a square IS indeed a rectangle - but that's because, in geometry like in functional programming, there is no concept of "mutating" an object!-).

like image 35
Alex Martelli Avatar answered May 15 '26 21:05

Alex Martelli



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!