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?
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.
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.