samedi 12 mars 2016

When creating a builder with a superclass, parent cannot return instance of child class

If I am using the builder pattern to configure new objects I may have two classes like Game and HockeyGame (shown below). When I want to create a new HockeyGame, I get it's builder and start calling methods to configure the object as needed.

The problem I am running into is shown in the main function. Once I call one method from the super class it returns as an intance of Game.Builder, and I can no longer call any method from the child class.

What is the best way to deal with this?

Main.java

class Main {

    public static void main(String[] args){

        HockeyGame hg = new HockeyGame.Builder()
                .setScore(5)
                .setTimeLimit(3600)
//--------------------------------------------------------------------
                .setIceTemperature(-5) // Error! Cannot call setIceTempurature() on
                                       // an instance of Game.Builder
//--------------------------------------------------------------------
                .build();


    }
}

Game.java

public class Game{

    int score;
    int timeLimit;

    public Game(int score, int timeLimit) {
        this.score = score;
        this.timeLimit = timeLimit;
    }

    public static class Builder {

        int score;
        int timeLimit;

        public Builder setScore(int score) {
            this.score = score;
            return this;
        }

        public Builder setTimeLimit(int timeLimit) {
            this.timeLimit = timeLimit;
            return this;
        }

        public Game build() {
            return new Game(score, timeLimit);
        }
    }
}

HockeyGame.java

public class HockeyGame extends Game {

    float iceTemperature;

    public HockeyGame(int score, int timeLimit, float iceTemperature) {
        super(score, timeLimit);
        this.iceTemperature = iceTemperature;
    }

    public static class Builder extends Game.Builder {

        float iceTemperature;

        public void setIceTemperature(float iceTemperature) {
            this.iceTemperature = iceTemperature;
        }

        public HockeyGame build(){
            return new HockeyGame(score, timeLimit, iceTemperature);
        }
    }
}

Thanks.

Aucun commentaire:

Enregistrer un commentaire