I have an application which is written in Java. I have 3 classes mysql_query, tablesetup, table_action. Now inside the class of each of the class I have created the object of other classes which results in recursive object invocation. What are the alternative that I can use to fix this problem ?
For Example:
In mysql_query.java i have
public class mysql_query{
tablesetup tablesetup = new tablesetup();
table_action table_action = new table_action();
}
In tablesetup.java I have
public class tablesetup{
mysql_query mysql_query= new mysql_query();
table_action table_action = new table_action();
}
Similarly in table_action.java I have
public class table_action{
mysql_query mysql_query= new mysql_query();
tablesetup tablesetup= new tablesetup();
}
–EDIT–
passing one class object to the constructor of other will not workout in my case as I have many dependent classes like this. So usually how programmers arrange these classes ? Can I use interface ? Is it appropriate to use in this case ?
tablesetupyou are instantiating atable_actiontable_actionyou are instantiating atablesetupI guess you see the loop – the first creates a new instance of the second which creates a new instance of the first, which creates a new instance of the second, and so on until your stack (holding method and constructor calls) is filled.
A little more clarification – when you instantiate an object through its constructor, all of its fields are initialized. So when you instantiate
table_action,new tablesetup()is invoked in order to initialize thetablesetuptablesetupvariable.Circular dependencies are not a good thing, but you can have them. You just need to pass a reference to an existing
tablesetupwhen creatingtable_actions.Apart from that – you are not using proper java naming. You should not use lowercase classes and underscores. The proper names are
TableSetup,TableActionandMySQLQuery. Same goes for variable names, apart from the upper-case. They should bymysqlQuery,tableSetup, etc.