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

后端 未结 2 758
暗喜
暗喜 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: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 reservations;
    

    to

    private ArrayList reservations = new ArrayList();
    

    And in your makeReservation method of Hotel class do this:

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

提交回复
热议问题