starkk92 starkk92 - 1 year ago 97
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.

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download