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

后端 未结 2 754
暗喜
暗喜 2021-01-27 20:44

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 field

相关标签:
2条回答
  • 2021-01-27 21:03

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

    0 讨论(0)
  • 2021-01-27 21:10

    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);
    
    0 讨论(0)
提交回复
热议问题