You could create a a Town
class as well. So, State has a field called capital of type Town. State also has a `Set' of towns so that all the towns can be looked up for a state. Town has a field state of type State. Something like below.
State class:
public class State {
private Town capital;
private Set<Town> towns;
public State() {
this.towns = new HashSet();
}
public State(Town capital) {
this.capital = captial;
this.towns = newHashSet();
this.towns.add(capital)
}
public void setCapital(Town capital) {
this.captial = capital;
}
public Town getCapital() {
return this.capital;
}
public void addTown(Town town) {
this.towns.add(town)
}
public Set getTowns() {
return this.towns;
}
}
Town class:
public class Town {
private State state;
public Town() {}
public Town(State state) {
this.state = state;
this.state.addTown(this);
}
public void setState(State state) {
this.state = state;
this.state.addTown(this);
}
public State getState() {
return this.state;
}
}
Then if you have a Town
object called myTown
, to get the town's state's capital you use:
myTown.getState().getCapital();
If you have a State
object called myState
, you get all the town's you use:
myState.getTowns();