In Java all the variables are references, so when you do
HotelRoom newRoom = room;
you are actually just copying the memory address from room
and it is saved in newRoom
, so, when you change something in newRoom
you are also changing room
because both variables point to the same address.
You can add a copy()
method (or just implement the clone()
method) in the HotelRoom class
public HotelRoom copy() {
Room newRoom = new Room();
newRoom.member0 = this.member0;
...
newRoom.membern = this.membern;
return newRoom;
}
which create a new instance and copy all the members, so, you can safely do HotelRoom newRoom = room.copy()
and now you will have two variables with the same members but in different memory address, so newRoom won't change the room object. Be careful, if one of your members is another object, you will need to copy (or clone) that member as well