【发布时间】:2015-12-04 19:58:39
【问题描述】:
更好的是:通过构造函数传递对象并将其保存到另一个类中的新引用,还是通过构造函数直接传递给方法?有什么区别吗?
class A
{
int a;
int b;
}
class B
{
public A refA;
public B(A refA)
{
this.refA = refA;
methodInB(refA);
}
public void methodInB(A refA)
{
...
}
}
或者 ---------------------------------------------- ---- 或者
class A
{
int a;
int b;
}
class B
{
public B(A refA)
{
methodInB(refA);
}
public void methodInB(A refA)
{
...
}
}
【问题讨论】:
-
您需要存储的参考吗?在这两种情况下,您都将引用直接传递给方法。存储更少实际上是可取的。
-
你需要
B吗?如果是,请设置它。如果没有,不要。没有“首选”方式,因为它们是两个不同的 sn-ps。 -
视情况而定。一般来说,我认为第一个是首选。类应该封装它们的行为。但是,在这种情况下,您正在 调用 ctor 的可覆盖方法。这是不好的做法。
methodInB()应该是私有的或最终的。 -
你的类
B是否需要A类型的类变量? -
如果您将 refA 存储为变量,那么为什么还要将其传递给 methodInB?除非 methodInB 将在其他地方与不同的 A 对象一起使用。
标签: java object constructor