Is there a way to refer to the current type with a type variable?

后端 未结 7 1682
悲&欢浪女
悲&欢浪女 2020-11-22 03:01

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

7条回答
  •  广开言路
    2020-11-22 04:03

    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);
            }
    
        }
    

提交回复
热议问题