starkk92 starkk92 - 4 months ago 16
Java Question

cast to Type in java

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

http://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.

Answer

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.

Comments