Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic? -
i'm bit confused how java generics handle inheritance / polymorphism.
assume following hierarchy -
animal (parent)
dog - cat (children)
so suppose have method dosomething(list<animal> animals). rules of inheritance , polymorphism, assume list<dog> is list<animal> , list<cat> is list<animal> - , either 1 passed method. not so. if want achieve behavior, have explicitly tell method accept list of subset of animal saying dosomething(list<? extends animal> animals).
i understand java's behavior. question why? why polymorphism implicit, when comes generics must specified?
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 arraylist<dog>(); // arraylist implements list 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