• 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
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

Two ways of calling a method

 
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I was watching a tutorial about generics and I noticed something. Maybe this is just a demonstration and nothing more, just wanted to confirm here. I understood Generics btw.

So in the below code, we can call "show()" method directly using juice.show();. But what is the use creating liquid variable in Glass class and then assigning it to "Juice" object reference and then creating another Juice type to make it work?

Is this something I can ignore and it was just the tutor trying to demonstrate Generics?








 
Saloon Keeper
Posts: 14270
321
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, I think it's just a demonstration that you can assign the liquid to a variable of type Juice, thanks to generics. The author probably also declared a new variable so that they can show that the values are identical.
 
Sheriff
Posts: 17086
298
Mac Android IntelliJ IDE Eclipse IDE Spring Debian Java Ubuntu Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It's a demonstration of the extent to which generics can help the compiler guard against type mismatch errors.

If you added this:

and tried to write this:

you'd get a compile-time error on line 4. The example shows that even though the liquid field in Glass<T> does not say exactly what type T is, the compiler has enough information from the Glass<Beer> declaration to figure out that the Juice j = mug.liquid assignment statement is not valid. Again, that determination is made from the Glass<Beer> declaration; the field declaration T liquid in the Glass class doesn't provide enough information.
 
Well THAT's new! Comfort me, reliable tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic