java - Return subclass when superclass is defined as return type -
this question has answer here:
in extension of question same topic: is list<dog> subclass of list<animal>? why aren't java's generics implicitly polymorphic? had follow-up question.
given have classes animal - parent dog - child
why can't return list when defined return type list?
private class animal{}; private class dog extends animal{}; public list<animal> makeanimallistofdogs(dog dog1, dog dog2){ list<dog> dogs = new list<dog>; dogs.add(dog1); dogs.add(dog2); return dogs; } this might seem useless example, clarify problem. if try this, error:
type mismatch: cannot convert list<dog> list<animal> it off course possible replacing return dogs following snippet
list<animal> animals = new arraylist<animals>(); animals.addall(dogs) return animals; so problem not how make work, why doesn't work. list dogs list containing animals, given fact dog animal, right?
see john skeet's answer question linked yourself:
no, list<dog> not list<animal>. consider can list<animal> - can add any animal it... including cat. now, can logically add cat litter of puppies? absolutely not.
// illegal code - because otherwise life bad list<dog> dogs = new list<dog>(); list<animal> animals = dogs; // awooga awooga animals.add(new cat()); dog dog = dogs.get(0); // should safe, right? suddenly have very confused cat.
now, can't add cat list<? extends animal> because don't know it's list<cat>. can retrieve value , know animal, can't add arbitrary animals. reverse true list<? super animal> - in case can add animal safely, don't know might retrieved it, because list<object>.
Comments
Post a Comment