Matthew Brown wrote:You can add both Cats and Dogs in the main method because it's a List<Animal>. Dogs and cats are both animals, so there's no problem there.
Matthew Brown wrote:
In the addAnimal method, it's declared as a List<? super Dog>. So it could be a List<Dog>, a List<Animal>, or a List<Object>. The one thing you can guarantee is that it will be able to accept a Dog, and all subclasses of Dog. But you couldn't add a Cat at this point, because that isn't safe (e.g. if it turns out to be a List<Dog>).
Matthew Brown wrote:
Does that help? I think the easiest way to understand wildcards is to ask "what actual types are allowed here?". If the operation makes sense for all possible types, then it makes sense for the wildcard. If it won't work for just one possible type, then you can't do it.
adithya narayan wrote:So, in a way we are breaking the code by adding Cats,Dogs, etc.(various subclasses of Animal) in the main() and passing the list to the addAnimal() method right ?
adithya narayan wrote:Here lies my question. If we tell the addAnimal(List<? super Dog> animals) method that please accept any list which is of type Dog or higher than that then ideally it should also let me add anything that is of type Dog or anything higher than that.
OCPJP6-05-11
"Your life is in your hands, to make of it what you choose."
Matthew Brown wrote:
adithya narayan wrote:Here lies my question. If we tell the addAnimal(List<? super Dog> animals) method that please accept any list which is of type Dog or higher than that then ideally it should also let me add anything that is of type Dog or anything higher than that.
No. That's a common mistake, but that's not what it means. It doesn't mean that you've got a list that can take any type higher than Dog. It means that you've got a specific List of an unknown type (where the unknown type is a Dog or higher). So, for instance, it could be a List<Dog>. What would you expect to be able to add to that?
List<? extends Animal> works under similar principles. The actual List has to be of a specific type, and that type can be Animal or any subclass. So it could be a List<Animal>, List<Dog>, List<GoldenRetriever>, List<Mouse>, etc. Can you think of any object that would be safe to add into all those? There isn't one. That's why you can't add anything to a List<? extends Xxx>.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime. |