如何在java中将在一个类中创建的对象传递给另一个类?

我正在努力开发一个在线酒店预订系统。 我有一个主要类,它接收用户的输入,例如他们的名字,他们的支付信息和其他数据字段,并使用该信息制作一个Reservation对象。 我有另一个名为Room类,它有一个每个Room对象的Reservations列表。 我遇到的问题是我无法找到一种方法将Reservation对象添加到Room对象的列表中。 以下是一些代码:

 public class HotelReservationSystem { private Reservation reservation; public void makeReservation(int checkIn, int checkOut)//Other parameters { reservation = new Reservation(checkIn, checkOut); } } public class Room { private ArrayList reservations; public void addReservation(//parameters?) { reservations.add(//parameter?); } } 

我不知道如何将新的Reservation对象作为Room类中add方法的参数传递。 我只是无法绕过它,并希望有人帮我慢慢思考我的思维过程。

谢谢你的帮助。

让makeReservation返回创建的Reservation对象:

  public Reservation makeReservation(int checkIn, int checkOut)//Other parameters { reservation = new Reservation(checkIn, checkOut); return reservation; } 

(您也可以创建一个reservation的getter)

然后像这样更改你的addReservation:

 public void addReservation(Reservation res) { reservations.add(res); } 

然后只需添加如下:

 HotelReservationSystem hrs = new HotelReservationSystem(); Reservation res = hrs.makeReservation(); Room room = new Room(); room.addReservation(res); 

但是,您可能想重新考虑您的模型。 现在你的HotelReservationSystem正在创建一个预订,只保存一个,覆盖旧的。 如果您创建多个会发生什么? 另外,如果给出HotelReservationSystem对象,您如何获得某个房间的预订? 只是要考虑一些事情……

我相信你一定是试过这个

 public void addReservation(Reservation reservation) { reservations.add(reservation); } 

但问题是你的列表reservations为空并将抛出空指针exception。 所以最好在声明时初始化它。 所以改变这个

 private ArrayList reservations; 

 private ArrayList reservations = new ArrayList(); 

在您的Hotel类的makeReservation方法中执行以下操作:

 Room room = new Room(); room.addReservation(reservation);