I'm trying to subclass a Builder class, as described in Subclassing a Java Builder class.
The solution given there is pretty simple. Here is the base class:
public class NutritionFacts {
private final int calories;
public static class Builder<T extends Builder> {
private int calories = 0;
public Builder() {}
public T calories(int val) {
calories = val;
return (T) this;
}
public NutritionFacts build() { return new NutritionFacts(this); }
}
protected NutritionFacts(Builder builder) {
calories = builder.calories;
}
}
And the subclass:
public class GMOFacts extends NutritionFacts {
private final boolean hasGMO;
public static class Builder extends NutritionFacts.Builder<Builder> {
private boolean hasGMO = false;
public Builder() {}
public Builder GMO(boolean val) {
hasGMO = val;
return this;
}
public GMOFacts build() { return new GMOFacts(this); }
}
protected GMOFacts(Builder builder) {
super(builder);
hasGMO = builder.hasGMO;
}
}
However, the return (T) this;
in NutritionFacts.Builder#calories(int)
results in a
NutritionFacts.java uses unchecked or unsafe operations
warning.
Given the generics, why is this cast unsafe? I know that T extends Builder
and that this
is a Builder
, so why is the cast from this
(Builder
) to T
(extends Builder
) unsafe? The cast should never fail, right?