I am working on elevator problem in Java. One of the problems I am coming across is how to assign object to objects. For example there are 7 floors and each floor is an object. So...
-
I would have a field in the passenger list that lists what floor they are a part of. That or you can have each floor hold a list of passengers that belong on that floor. The second solution seems more natural, as what happens if you have a passenger that doesn't live on any floors? You seem to be mostly right on trackBrendan Lesniak– Brendan Lesniak2014-03-22 20:25:36 +00:00Commented Mar 22, 2014 at 20:25
4 Answers
I feel that residence floor is a field that belongs to the resident. Simply, hold a Floor object in your Passenger object.
public class Passenger {
private Floor residenceFloor;
public void setResidenceFloor(Floor residenceFloor) {
this.residenceFloor = residenceFloor;
}
public Floor getResidenceFloor() {
return residenceFloor;
}
}
When evaluating whether a resident belongs to a certain floor simply use an overriden equals method for your Floor object.
Floor f1 = new Floor();
Passenger p1 = new Passenger();
p1.setResidenceFloor(f1);
if (f1.equals(p1.gerResidenceFloor()) {
// p1 is a resident of f1
}
You could also hold a Set of residents in your Floor objects. These are just two different OOP styles.
Comments
Not sure what your overall goal or usage is, but it seems like giving the Floor class a field floorNumber that is set by a constructor could give some added flexibility.
Floor floor1 = new Floor(1);
Then just have residenceFloor be a field of Passenger:
public class Passenger {
private int residenceFloor;
public void setResidenceFloor(Floor residenceFloor) {
this.residenceFloor = residenceFloor.floorNumber;
}
public Floor getResidenceFloor() {
return residenceFloor;
}
}
Having floor number as a field just seems more useful to me, as it allows an easy way to have other methods/fields refer to it. Passengers could have currentFloor fields for where they are at the moment, or residents might move to a different floor, and any method that needed to change or set a floor state could just use floorNumber of whatever floor you passed it.