简体   繁体   中英

How do I pass an object created in one class to another in java?

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?);
    }
}

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.

Thanks for your help.

Let makeReservation return the created Reservation object:

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

(You could also create a getter for reservation )

Then change your addReservation like this:

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

And then just add it like this:

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

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...

I believe you must have tried this

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

but the problem here is that your list reservations is null and will throw null pointer exception. So better initialize it at declaration. So change this

private ArrayList<Reservation> reservations;

to

private ArrayList<Reservation> reservations = new ArrayList<Reservation>();

And in your makeReservation method of Hotel class do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM