gpt4 book ai didi

java - 使用父类(super class)创建构建器时,父类不能返回子类的实例

转载 作者:塔克拉玛干 更新时间:2023-11-01 23:08:13 25 4
gpt4 key购买 nike

<分区>

如果我使用构建器模式来配置新对象,我可能有两个类,如 GameHockeyGame(如下所示)。当我想创建一个新的 HockeyGame 时,我得到它的构建器并开始调用方法来根据需要配置对象。

我遇到的问题显示在主函数中。一旦我从父类(super class)中调用一个方法,它就会作为 Game.Builder 的实例返回,并且我不能再从子类中调用任何方法。

处理这个问题的最佳方法是什么?

主.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();


}
}

游戏.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 HockeyGame.Buidler setIceTemperature(float iceTemperature) {
this.iceTemperature = iceTemperature;
return this;
}

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

谢谢。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com