• 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:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Declaration of return value in generic methods

 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

I try the following 4 tests about generic methods (where Dog extends Animals extends Object ):



Here test1 and test2 compile fine, as expected. I also understand that test3 not compiles (Object not extends Animal, so the assignment is not allowed). Now I expect that compilation should fail for test4 also, because upper bound for placeholder E is Object here. Therefore it's possible, that testFunc4 returns (in worst case) a List of Objects, which can't be assigned to list4(Type: List<? extends Animal>). But to my surprise test4 compiles??.

Why does test4 compile?

Thanks,
Thomas


 
Saloon Keeper
Posts: 15524
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because the methods returns a List<E>, where E is inferred from the formal type of the variable you're trying to assign the return value to.

In this case, the return type automatically adapts to the type required by the variable.
 
Thomas Hermann
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I think, I understand now.

Just as for generic classes the concrete generic type is determined during instantiation, the concrete type for the return value (List<E>) of the generic function is determined by the caller during the assignment.

Thanks to Stephan van Hulst,

Thomas
 
reply
    Bookmark Topic Watch Topic
  • New Topic