• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Generic SuperType confusing

 
Greenhorn
Posts: 24
2
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Greenhorn
Posts: 6
6
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 24
2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Tamas for such a long and detailed explanation. It's clear now. Thanks again...!!!
 
reply
    Bookmark Topic Watch Topic
  • New Topic