When I was working on my project and had to use a lot of nested objects, I became very unsure of my structure design in Java, when I wanted to set the instance variable of a deeply nested object from the top object, It seems to me that I missed a basic understanding, possibly structured Java design. Any understanding of this is appreciated.
Imagine that I have an object that has a logical structure in which nested sub-objects are variables. For instance:
Country Capital Palace King
If now I want to set the private variable String 'nameOfKing' to King from the main object (Country), I will need to define each method in all the upper King classes. 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 itβs fine if you have only a few variables, but what if the King, Palace, Capital classes have many other variables and methods, and all of them must be called from the country. What if the Palace also contains other class objects, such as (just creating things now) ThroneRoom, Treasury, Queen, etc. This will mean that for almost all methods in subclasses it is necessary to exist in the Country class, which could potentially mean that you need to create a huge number of methods just to pass information to auxiliary objects, which leads to a very large Country class.
Now, I suppose, you could technically say that a king can also be defined in the country itself, eliminating unnecessary methods in the palace and the capital, but this still means that the methods must exist in the Country class, and that if this structure has meaning, as in logic grouped together, what would be the best approach for this? I'm not sure there is a better way, but I cannot shake the feeling that something is missing here.