Subtyping Java Generics: A lion cage is not an animal cage!
from Generics > Subtyping.
If on the one hand you maintain that English is ambiguous;
But what about an "animal cage"? English is ambiguous, so to be precise let's assume we're talking about an "all-animal cage"...and then follow up with a justification which for all intents and purposes seems to be based on that ambiguousness;
Since a lion is a kind of animal (Lion is a subtype of Animal), the question then becomes, "Is a lion cage a kind of animal cage? Is Cage<Lion> a subtype of Cage<Animal>?". By the above definition of animal cage, the answer must be "no". This is surprising! But it makes perfect sense when you think about it: A lion cage cannot be assumed to keep in butterflies, and a butterfly cage cannot be assumed to hold in lions. Therefore, neither cage can be considered an "all-animal" cage:I think you have a problem.
I guess that's the price you pay for trying to fit a less expressive language (Java) into something as "ambiguous" as English? Either way, to deduce that it's perfectly natural to conclude that a lion cage isn't the same as an animal cage in such a fashion seems a bit far fetched.
How about admitting that type inheritance doesn't work here? A lion cage certainly *is* a type of animal cage goddamnit. I can see that mixing types like this could break polymorphism - I take the point that a butterfly cage wouldn't be suitable to hold lions, and vice versa. However it seems like an awful kludge to expect people to understand polymorphism in terms of single classes in one way, and then tell them that generics "improves" on this to prevent lion cages from trying to hold butterflies. Mother of Mary!
Update:
Haha! Hillarious. Let's invent another concept and call it bounded wildcards to fix this problem. This seems like a hack though doesn't it? My god:
While Cage<Lion> and Cage<Butterfly> are not subtypes of Cage<Animal>, they are in fact subtypes of Cage<? extends Animal>I'm sure this has to do with covariance, but I don't understand this, and I'm pretty sure Larry Wall would cry into his moustache while agreeing with me (though he might like the punctuation character syntax :)).
Other Java Generics links:
Java theory and practice: Generics gotchas
The Java Tutorials - Lesson: Generics
Generics in the Java Programming Language
No comments:
Post a Comment