• Post Reply Bookmark Topic Watch Topic
  • New Topic

Generic SuperType confusing  RSS feed

 
Manoj Shekhawat
Greenhorn
Posts: 8
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Super generic type means, class or it's super class.

So IOException have Exception and Object as it's super classes. right?

Then why we get compiler error while trying to add Exception to the list of exception?



And how come we add FileNotFoundException which is subclass of IOException.

This is from OCP Oracle® Certified Professional Java® SE 8 Programmer II book By: Jeanne Boyarsky; Scott Selikoff from Chapter 3.
 
Tamas Szekeres
Greenhorn
Posts: 6
6
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since this is a super generic type, it means that all four of these are valid:
However, this is invalid:You don't know which specific list out of the possible four will be assigned to the variable, so you must ensure that whatever you're putting into it is going to be compatible with all of them:Therefore in this case you can only put objects which are the same as the class or its child classes, but not their parents: IOException, FileNotFoundException, etc.

By the way, this is the exact same reason why you cannot add any objects to a list with an extends generic type.There you do not have a most specific class that can possibly fit into any of these, as none of them are final and so can have child classes on their own that we might not even know about when we're writing our codes. If one of them were final, like String, you could have a most specific final class, but in this case there's no point using the ? extends struct, because there can not be any child classes.
 
Manoj Shekhawat
Greenhorn
Posts: 8
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Tamas for such a long and detailed explanation. It's clear now. Thanks again...!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!