Polymorphism and Generics continues…

Screen Shot 2018-11-11 at 12.19.43 PM

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

Screen Shot 2018-11-11 at 12.29.56 PM

The below code compiles fines.

Screen Shot 2018-11-11 at 12.32.47 PM

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.

Screen Shot 2018-11-11 at 12.36.27 PM

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.

Screen Shot 2018-11-11 at 12.41.59 PM

The above code compiles fine. We added a Dog Object to the List 🙂

Screen Shot 2018-11-11 at 12.43.32 PM

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.

Leave a Reply

Your email address will not be published. Required fields are marked *