starkk92 starkk92 - 7 months ago 52
Java Question

cast to Type in java

I am new to generics and was looking at this answer:

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

How does the cast work here? I was expecting
here, since we are casting a pure superclass object to subclass.


You're not casting superclass object to subclass there. For GMOFacts.Builder object, the calories method would be type erased to something like this:

public GMOFacts.Builder calories(int val) {
        calories = val;
        return (GMOFacts.Builder) this;

And this reference points to GMOFacts.Builder object anyways, so it's a valid type cast.