gpt4 book ai didi

java - 我可以在不完全填充对象的情况下使用它们吗?

转载 作者:行者123 更新时间:2023-12-04 14:35:26 25 4
gpt4 key购买 nike

我有情况。我必须在 JAVA 中创建一个体育俱乐部系统。应该有一个类用于跟踪俱乐部名称、主席姓名和俱乐部的分支机构。对于每个体育分支,还应该有一个类来跟踪运动员名单。此外,每个球员都应该有姓名、号码、职位和薪水。所以,我想出了这个。三个独立的类:

public class Team
{
String clubName;
String preName;
Branch []branches;
}

public class Branch
{
Player[] players;

}

public class Player
{
String name;
String pos;
int salary;
int number;
}

问题是在另一个类中创建 Branch[] 以及在 Player[] 中创建 Branch[]。有没有更简单的方法来做到这一点?例如,我只想添加俱乐部名称、主席姓名和俱乐部分支机构的信息,在这种情况下,我不必输入球员、姓名、薪水等,因为它们是相互嵌套的。我希望我能说清楚。如有其他问题,您可以提出。

最佳答案

这是使用常规 Accessors/Mutators 的更完整、更正式的场景示例( setter/getter / setter/getter ),constructors , 和 Lists .下面的 main() 方法说明了如何使用您的类。

public class SportsClub
{
public static void main(String[] args)
{
//Create a team without any branches
Team myTeam = new Team("Southpaws", "South");

//Create a new Branch without any players
Branch myBranch = new Branch();

//Add myBranch to myTeam
myTeam.getBranches().add(myBranch);

//Create a new player
Player myPlayer = new Player("Bob", "Center", 120, 3);

//Add myPlayer to myBranch (and therefore myTeam)
myBranch.getPlayers().add(player);
}
}


public class Team
{
private String clubName;
private String preName;
private List<Branch> branches;

public Team(String clubName, String preName)
{
this.clubName = clubName;
this.preName = preName;
branches = new ArrayList<Branch>();
}

public String getClubName() { return clubName; }
public String getPreName() { return preName; }
public List<Branch> getBranches() { return branches; }

public void setClubName(String clubName) { this.clubName = clubName; }
public void setPreName(String preName) { this.preName = preName; }
public void setBranches(List<Branch> branches) { this.branches = branches; }
}

public class Branch
{
private List<Player> players = new ArrayList<Player>();

public Branch() {}

public List<Player> getPlayers() { return players; }
public void setPlayers(List<Player> players) { this.players = players; }
}

public class Player
{
private String name;
private String pos;
private Integer salary;
private Integer number;

public Player(String name, String pos, Integer salary, Integer number)
{
this.name = name;
this.pos = pos;
this.salary = salary;
this.number = number;
}

public String getName() { return name; }
public String getPos() { return pos; }
public Integer getSalary() { return salary; }
public Integer getNumber() { return number; }

public void setName(String name) { this.name = name; }
public void setPos(String pos) { this.pos = pos; }
public void setSalary(Integer salary) { this.salary = salary; }
public void setNumber(Integer number) { this.number = number; }
}

要回答您的问题,是的,您可以创建这些对象而无需使用玩家填充 List。上面的 SportsClub.main() 说明了这一点。

关于java - 我可以在不完全填充对象的情况下使用它们吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3001220/

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