I am new to generics and was looking at this answer:
https://stackoverflow.com/a/17165079/1632141
It works perfectly, however I couldn't understand how this part of the code works.
public T calories(int val) {
calories = val;
return (T) this;
}
in the inner class of the NutritionFacts
.
How does the cast work here? I was expecting java.lang.ClassCastException
here, since we are casting a pure superclass object to subclass.