gpt4 book ai didi

Java构造函数重载歧义

转载 作者:行者123 更新时间:2023-12-01 18:47:47 26 4
gpt4 key购买 nike

如何解决以下构造函数重载问题?这是一个面试问题,但我很想知道解决方案。

class Player
{
int nationalRank;
int internationalRank;
String name;

Player(String name, int nationalRank)
{
this.name= name;
this.nationalRank = nationalRank;
this.internationalRank=0;
}

Player(String name, int internationalRank)
{
this.name= name;
this.nationalRank = 0;
this.internationalRank=internationalRank;
}
}

这里,编译器将给出错误,因为两个构造函数的参数类型相同。但从逻辑上来说,两者是不同的。如何在不添加任何额外参数的情况下解决这个问题?有没有专门针对这个的设计模式?

最佳答案

class Player
{
int nationalRank;
int internationalRank;
String name;

private Player(){}

public static Builder builder()
{
return new Builder();
}

public static class Builder
{
int nationalRank = -1;
int internationalRank = -1;
String name;

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

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

public Builder name(String name)
{
this.name = name;
return this;
}

public Player build()
{
if (nationalRank == -1 && internationalRank = -1)
throw new IllegalStateException("both ranks haven't been initialized");
if (null == name)
throw new IllegalStateException("name hasn't been initialized");
Player result = new Player();
result.nationalRank = this.nationalRank;
result.internationalRank = this.internationalRank;
result.name = this.name;
return result;
}
}
}

用法:

Player player = Player.builder().name("John").internationalRank(522).build();

关于Java构造函数重载歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16978551/

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