Java: Passing the same objects to each others constructor

前端 未结 6 2276
粉色の甜心
粉色の甜心 2021-01-21 10:56

Evening everyone.

I seem to have hit an odd problem when trying to pass an object to another objects constructor who\'s constructor also relies on the object it\'s being

6条回答
  •  不知归路
    2021-01-21 11:07

    This will lead to problems as you can see. Instead of this approach, you can use the setter-getter method approach where you construct the object with a default constructor such as

    ToolBar myToolBar = new ToolBar();
    WebPanel webPanel = new WebPanel();
    

    and then use the setter methods to set the required instance variables which are required for the object to be fully constructed.

    myToolBar.setWebPanel(webPanel);
    webPanel.setToolBar(myToolBar);
    

提交回复
热议问题