Java:将相同的对象传递给彼此的构造函数 [英] Java: Passing the same objects to each others constructor

查看:77
本文介绍了Java:将相同的对象传递给彼此的构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

甚至每个人。

当试图将一个对象传递给另一个对象构造函数时,我似乎遇到了一个奇怪的问题,该对象的构造函数还依赖于要传递给它的对象。

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 passed to.

例如,使用以下示例:

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

但是在构造ToolBar时,它返回NullPointerException。当然,这是因为尚未构建webPanel并需要它。

However when constructing ToolBar it returns a NullPointerException. Ofcourse that's because webPanel isn't constructed yet and it requires it.

减速和初始化两者都必须保留在同一类(称为BuildUI)中,因为这是我设置的位置属性。 (使用ToolBar创建webPanel对象也没有意义,反之亦然)。

Both of the decelerations and initialization must remain in the same class (called BuildUI) since it's where I set up the properties. (It also doesn't make sense for a ToolBar to create a webPanel object and vice versa).

我也不知道这是否是一种好的编程习惯,因为这两个对象都需要互相引用。

I'm also not sure if that's even good programming practice, since both objects require references to each other.

在此提出的任何建议都值得赞赏。谢谢,汤姆。

Any advice here is much appreciated. Thanks, Tom.

推荐答案

这将导致问题,如您所见。代替这种方法,可以使用setter-getter方法,在该方法中使用默认构造函数构造对象,例如

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();

,然后使用setter方法设置所需的实例变量,这些变量对于对象是完全必需的

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);

这篇关于Java:将相同的对象传递给彼此的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆