mardi 15 août 2017

Builder pattern with inheritance suppport generics issue

I implemented pattern based on this answer I have the following asbtract config:

public abstract class AbstractConfig {

    public static abstract class Builder<B extends Builder<B>> {

        private int calories = 0;

        public Builder() {

        }

        public B setCalories(int calories) {
            this.calories = calories;
            return (B) this;
        }

        public abstract AbstractConfig build();
    }

    private int calories = 0;

    protected AbstractComponentConfig(final Builder builder) {
        calories = builder.calories;
    }
}

And I have the following concrete config:

public final class DialogConfig extends AbstractConfig {

    public static class DialogConfigBuilder<B extends DialogConfigBuilder<B>> extends Builder<B> {

        private double width;

        private double height;

        public DialogConfigBuilder() {
            //does nothing.
        }

        public B setWidth(final double value) {
            width = value;
            return (B) this;
        }

        public B setHeight(final double value) {
            height = value;
            return (B) this;
        }
        public DialogConfig build() {
            return new DialogConfig(this);
        }
    }

    private final double width;

    private final double height;

    protected DialogConfig(final DialogConfigBuilder builder) {
        super(builder);
        width = builder.width;
        height = builder.height;
    }

    public double getWidth() {
        return width;
    }

    public double getHeight() {
        return height;
    }
}

And this is how I use it

DialogConfig config = new DialogConfig.DialogConfigBuilder()
                .setWidth(0)
                .setCalories(0)
                .setHeight(0) //X LINE
                .build();

At X line I get - Can't find symbol method setHeight. What is my mistake?

EDIT - I will have and a SuperDialogConfig that must extend DialogConfig and etc. I mean there will be other subclasses.

Aucun commentaire:

Enregistrer un commentaire