Is List<Dog> a subclass of List<Animal>? Why are generics in Java not polymorphic?
Hello colleagues! I'm new to Java and trying to understand generics. I wrote a simple code, but the compiler complains, and I don't understand why.
I have a class hierarchy: Animal is the parent class, Dog extends Animal and Cat extends Animal.
Now I want to write a method that takes a list of animals and prints their names. Logically, if I pass a list of dogs there, it should work, because Dog is an Animal. But the compiler gives an error!
Here's the code:
```java
public class GenericsTest {
public static void main(String[] args) {
List dogs = new ArrayList<>();
dogs.add(new Dog("Rex"));
dogs.add(new Dog("Buddy"));
printAnimalNames(dogs); // Compilation error!
}
public static void printAnimalNames(List
No answers yet.
Log in to leave an answer
Blogs
Kotlin for Machine Learning: Capabilities and Limitations — Part 2
Swift Application Security: Top 10 Vulnerabilities for iOS/macOS