I'm working on a project for school that is challenging my understanding of OOP. I have multiple objects of the same class, City. Each City has a location. If my understanding is correct, since the distance between each City is dependent on another City "int distance" can't be a field within the class City. I can write a method to calculate the distance between each City, but I'm not sure how/where to save that data. I would like to eventually sort this data to find which City objects are in closest proximity.
I would suggest a Map
class (as in cartography, not the usual Collection
), whose instances would contain a Set
of Cities
. They could provide method to calculate additional information about the relations between their Cities
, and cache the result if needed.
It is not necessary that the Map
contains the Cities
but it sounds logical and will surely help manipulating them. If you don't want that you could use a "helper class", something like DistancesHelper
, defining static methods to work on Cities
that could interact with a static cache.
It seems to me that calculation of distance should be a method of Location
not a method of City
. You could later decide your map has other points of interest besides cities which also have a location.
So my suggestion of structure would be:
interface PointOfInterest {
Location getLocation();
default int distanceTo(PointOfInterest other) {
return getLocation().distanceTo(other.getLocation());
}
}
class City implements PointOfInterest {
private final Location location;
@Override public Location getLocation() {
return location;
}
}
class Location {
public int distanceTo(Location other) {
...
}
}
That way any data required to define location (eg latitude, longitude) is completely contained within the Location
object.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.