When I was working on a project of mine and had to use a lot of nested objects, I became very unsure of my design of structure in Java when I wanted to set an instance variable of a deeply nested object from the upper object. It feels like I miss a basic understanding perhaps of structured design in Java. Any insight in this is appreciated.
Imagine I have an object which has a logical structure of having nested sub objects as variables. For example:
Country
Capital
Palace
King
If I now want to set a private String variable 'nameOfKing' in King from the main object (Country), I would have to define every method in all upper classes of King. So something like this:
public class Country {
private Capital capital;
public void setNameOfKing(String n) {
capital.setNameOfKing(n);
}
}
public class Capital{
private Palace palace;
public void setNameOfKing(String n) {
palace.setNameOfKing(n);
}
}
public class Palace{
private King king;
public void setNameOfKing(String n) {
king.setNameOfKing(n);
}
}
public class King{
private String nameOfKing;
public void setNameOfKing(String n) {
this.nameOfKing = n;
}
}
so that I can call country.setNameOfKing(n);
. Now this is fine if you have just a few variables, but what if the classes King, Palace, Capital each have many other variables and methods defined and all of them have to be called from Country. What if Palace also contains other class objects like (just making stuff up now) ThroneRoom, Treasury, Queen, etc... It would mean that for almost all methods in the sub classes, one has to exist in the Country class, which could potentially mean you have to create a huge amount of methods simply for passing info to the sub objects resulting in a very large Country class.
Now I suppose you could technically say that King could also be defined in the Country itself, doing away with the extra methods in Palace and Capital, but it would still mean the methods have to exists in the Country class and what if this structure makes sense as in logic grouped together, what would be the best approach for this? I'm not sure there is a better way, but I can't shake the feeling I'm missing something here.