【问题标题】:How to set up object parameter by defualt默认情况下如何设置对象参数
【发布时间】:2022-12-11 22:03:37
【问题描述】:

是否可以如下所述设置对象的参数之一,但使其像类默认值一样,而不是每个对象的单独方法。

对象 object = new Object(a, b, c = a+b)

例如。

public FootballTeams(String name) {
    this.name = name;
    this.gamesQuant = 0;
    this.wins = 0;
    this.draws = 0;
    this.looses = 0;
    this.setPoints(this.wins,this.draws);
}
//constructor
public void setPoints(int wins, int draws) {
    this.points = this.wins*3+this.draws;
}

我试图在构造函数和设置器中设置它,但失败了,总是只计算初始值。 谢谢你。

【问题讨论】:

    标签: java object parameters


    【解决方案1】:

    不,您应该使用构造函数重载。

    public FootballTeams(String name) {
        this.name = name;
        this.gamesQuant = 0;
        this.wins = 0;
        this.draws = 0;
        this.looses = 0;
        this.setPoints(this.wins,this.draws);
    }
    
    
    public FootballTeams(String name, int gamesQuant) {
        this.name = name;
        this.gamesQuant = gamesQuant;
        this.wins = 0;
        this.draws = 0;
        this.looses = 0;
        this.setPoints(this.wins,this.draws);
    }
    

    或者您可以使用builder design pattern

    最终得到这样的结果(字段应该有默认值)。

    FootballTeams footballTeams = FootballTeams.builder()
        .name("name")
        .gamesQuant(1)
        .wins(1)
        .build();
    

    【讨论】:

      猜你喜欢
      • 2019-08-25
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多