如何在Java中将在一个类中创建的对象传递给另一个类?
我正在尝试开发在线酒店预订系统.我有一个主类,它从用户那里获取输入信息,例如他们的姓名,他们的支付信息和其他数据字段,并使用该信息创建一个Reservation
对象.我还有一个名为Room
的类,其中每个Room
对象都有一个Reservations
列表.我遇到的问题是我想不出一种方法来将Reservation
对象添加到Room
对象的列表中.这是一些代码:
I'm trying to develop an online hotel booking system. I have the main class which takes input from the user such as their name, their payment information, and other data fields and makes a Reservation
object using that information. I have another class called Room
that has a list of Reservations
for each Room
object. The problem I am having is I can't figure out a way to add the Reservation
object into the list in the Room
object. Here is some of the code:
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<Reservation> reservations;
public void addReservation(//parameters?)
{
reservations.add(//parameter?);
}
}
我不知道如何获取新的Reservation
对象作为Room
类中add
方法的参数传递.
我只是束手无策,希望有人能帮助我慢跑.
I don't know how to get the new Reservation
object to be passed as a parameter for the add
method in the Room
class.
I just can't wrap my head around it and was hoping for someone to help jog my thinking process.
感谢您的帮助.
让makeReservation返回创建的Reservation对象:
Let makeReservation return the created Reservation object:
public Reservation makeReservation(int checkIn, int checkOut)//Other parameters
{
reservation = new Reservation(checkIn, checkOut);
return reservation;
}
(您也可以为reservation
创建一个吸气剂)
(You could also create a getter for reservation
)
然后按如下所示更改您的addReservation:
Then change your addReservation like this:
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对象的情况下,如何获得某个房间的预订?只是要考虑的一些事情...
However, you might want to rethink your model. Right now your HotelReservationSystem
is creating a reservation and only saves that one, overwriting old ones. What happens if you create more than one? Also how can you get the reservations for a certain room given the HotelReservationSystem object? Just some things to think about...