gpt4 book ai didi

java - 设置和显示名称和电子邮件 Java 对象类

转载 作者:行者123 更新时间:2023-12-02 10:11:44 25 4
gpt4 key购买 nike

我有一个java类作业,它输入船员并显示他们的信息,我做过其他类似的案例,但不知道如何构建这个。我要创建两个类,Sailor 和 CrewMember,它们与这个 main 方法一起使用 -

import java.util.ArrayList;

public class SailorProgram {

public static void main(String[] args) {

Sailor firstSailor = new Sailor("Jimmy", "jimmy@mail.com");
Sailor secondSailor = new Sailor("Rose", "rose@mail.com");
Sailor thirdSailor = new Sailor("James", "james@sailors.com");


CrewMember firstCrew = new CrewMember();
CrewMember secondCrew = new CrewMember();

firstCrew.addCrewMember(firstSailor);
firstCrew.addCrewMember(secondSailor);

secondCrew.addCrewMember(thirdSailor);
secondCrew.addCrewMember(secondSailor);

System.out.println(" First crew \n" + firstCrew);
System.out.println(" Second crew \n" + secondCrew);

secondSailor.setEmail("Rose@sailors.com");
System.out.println(" Second crew \n" + secondCrew);
}
}

然后打印出来

First crew
Jimmy (jimmy@mail.com)
Rose (rose@mail.com)

Second crew
James (james@sailors.com)
Rose (rose@mail.com)

Second crew
James (james@sailors.com)
Rose (rose@sailors.com)

谢谢!

最佳答案

addCrewMember() 是我们想知道的关键方法。如果将 Sailor 引用给 secondCrew 类,输出将会改变。

public class Sailor {
private String name;
private String email;

public Sailor(String name, String email) {
this.name = name;
this.email = email;
}

@Override
public String toString() {return name + " " + "(" + email + ")";}
}

如果 CrewMember.class 像下面这样

import java.util.ArrayList;

public class CrewMember {

private final ArrayList<Sailor> sailors = new ArrayList<>();

public void addCrewMember(Sailor s) { //add sailors with this
sailors.add(s);
}
@Override
public String toString() { return sailors.toString(); }
}

并在问题中运行主要方法thr 输出是这样的:

 First crew 
[Jimmy (jimmy@mail.com), Rose (rose@mail.com)]

Second crew
[James (james@sailors.com), Rose (rose@mail.com)]

Second crew
[James (james@sailors.com), Rose (Rose@sailors.com)]

Rose@sailors.com 发生了变化!因为 ArrayList sailors 保存了 Rose Sailor 的引用

关于java - 设置和显示名称和电子邮件 Java 对象类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54959799/

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