Is List<Dog> a subclass of List<Animal>? Why is Java generic implicitly not guaranteed polymorphism?

Asked 2 years ago, Updated 2 years ago, 75 views

It's confusing how Java Generics deals with inheritance and polymorphism. Let's say there's a hierarchy like this. Animal (Parent) Dog - Cat (child)

Assuming that there is a DoSomething(List<Animal> animals) method in the above situation, List<Dog> and can be said to be the same as List<Animal> and based on the law of inheritance and polymorphism. But that's not true. To satisfy the above assumptions, you have to explicitly mark the method. In order to accept some child list of Animal as a factor in the method, I had to declare as follows. doSomething(List<? extends Animal> animals).

I think these are the principles of Java. I wonder why. Polymorphism in Java is usually implicit, but why is it different only in terms of generics?

inheritance java generics polymorphism

2022-09-21 20:28

1 Answers

No, List<Dog> and List<Animal> are not the same. Think about what you can do with List<Animal>. You can add any animal variable to List<Animal>. Including cat, of course. Logically, can I add a cat to a group of kittens? Absolutely not.

// Not a good code. 
List<Dog> dogs = new List<Dog>();
List<Animal> animals = dogs; //Invalid code.
animals.add(new Cat());
Dog dog = dogs.get(0); // Is it a safe code?

All of a sudden, the crowded cat will return. List<? Because extensions Animal> is List<Cat> unknown, List<? Unable to add cat to extensions Animal>. You can find the value in the list and you can see that it is Animal. But you can't add any animal. If it's the opposite (List<)? You can safely add Animal to the Super Animal) list. But you never know what will come out of the list. Because the list can be List<Object>.


2022-09-21 20:28

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.