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?
If this code worked, you could continue by inserting into
test2aCircle— thus utterly breaking the guarantee thattest1makes, that onlyRectangles 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!-).