如何在Java中将在一个类中创建的对象传递给另一个类? [英] How do I pass an object created in one class to another in java?

查看:897
本文介绍了如何在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...

这篇关于如何在Java中将在一个类中创建的对象传递给另一个类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆