Suppose I\'m trying to write a function to return an instance of the current type. Is there a way to make T
refer to the exact subtype (so T
should
I may not fully understood the question, but isn't it enough to just do this (notice casting to T):
private static class BodyBuilder {
private final int height;
private final String skinColor;
//default fields
private float bodyFat = 15;
private int weight = 60;
public BodyBuilder(int height, String color) {
this.height = height;
this.skinColor = color;
}
public T setBodyFat(float bodyFat) {
this.bodyFat = bodyFat;
return (T) this;
}
public T setWeight(int weight) {
this.weight = weight;
return (T) this;
}
public Body build() {
Body body = new Body();
body.height = height;
body.skinColor = skinColor;
body.bodyFat = bodyFat;
body.weight = weight;
return body;
}
}
then subclasses won't have to use overriding or covariance of types to make mother class methods return reference to them...
public class PersonBodyBuilder extends BodyBuilder {
public PersonBodyBuilder(int height, String color) {
super(height, color);
}
}