If this code worked, you could continue by inserting into test2
a Circle
-- thus utterly breaking the guarantee that test1
makes, that only Rectangle
s 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!-).