The compiler only allows the List of Type Animal to the method add. Otherwise , it throws compilation error.
Is there any work around , so that we can pass List of Type Dog or Cat to the method add.
The Answer is Yes. We can use the keyword “extends”
There IS a mechanism to tell the compiler that you can take any generic subtype of the declared argument type because you won’t be putting anything in the collection.
The method signature would change from
The below code compiles fines.
By saying <? extends Animal>, we’re saying, “I can be assigned a collection that is a subtype of List and typed for or anything that extends Animal. And oh yes, I SWEAR that I will not ADD anything into the collection.”
The below code will not compile as we are trying to add a Dog to the List.
Is there any way to add the Dog here?
The Answer again is Yes. You can use a wildcard AND still add to the collection, but in a safe way—the keyword super.
The above code compiles fine. We added a Dog Object to the List 🙂
The above code, says “Hey compiler, please accept any List with a generic type that is of type Dog, or a supertype of Dog. Nothing lower in the inheritance tree can come in, but anything higher than Dog is OK.”
If you pass in a list of type Animal, then it’s perfectly fine to add a Dog to it. If you pass in a list of type Dog, it’s perfectly fine to add a Dog to it. And if you pass in a list of type Object, it’s STILL fine to add a Dog to it.