Java对象的初始化顺序

时间:2013-06-02 19:57:23

标签: java object initialization

我只想在Java中实现对象,称为 “Family” 。在它的构造函数中,我希望这些对象链接到它们的邻居,所以当我创建一个 Family - Object时,我需要max。另外两个 系列 - 对象。

public class Family {

    Family leftNeighbour;
    Family rightNeighbour;

    public Family(Family leftNeighbour, Family rightNeighbour) {
        this.leftNeighbour = leftNeighbour;
        this.rightNeighbour = rightNeighbour;
    }   
}

现在,我开始启动三个家庭:A是第一个,所以它只有一个正确的邻居,B有两个,C是最后一个,只剩下一个邻居。

问题:

Family A = new Family(null,B);
Family B = new Family(A,C);
Family C = new Family(B, null);

我无法初始化A,因为B尚未创建。另外,我不能初始化B,因为A缺失了。有没有可能解决这个 没有 getter和setter(发现它有点难看,以防我需要大量的家庭对象)。

3 个答案:

答案 0 :(得分:5)

您可以将其添加到构造函数中:

if (leftNeighbour != null)
  leftNeighbour.rightNeighbour = this;
if (rightNeighbour != null)
  rightNeighbour.leftNeighbour = this;

然后:

Family A = new Family(null, null);
Family B = new Family(A, null);
Family C = new Family(B, null);

但这很容易出错。

更好的方法 - “makeNeighbours”方法:

public class Family {
    Family leftNeighbour;
    Family rightNeighbour;

    public Family() {}

    public static makeNeighbours(Family leftNeighbour, Family rightNeighbour)
    {
        leftNeighbour.rightNeighbour = rightNeighbour;
        rightNeighbour.leftNeighbour = leftNeighbour;
    }
}

然后:

Family A = new Family();
Family B = new Family();
Family C = new Family();
Family.makeNeighbours(A, B);
Family.makeNeighbours(B, C);

相关替代方案 - 让makeNeighbours采用可变数量的参数
(灵感来自雷托尔回答):

public static makeNeighbours(Family... families)
{
   for (int i = 1; i < families.length; i++)
   {
      families[i-1].rightNeighbour = families[i];
      families[i].leftNeighbour = families[i-1];
   }
}

然后:

Family A = new Family();
Family B = new Family();
Family C = new Family();
Family.makeNeighbours(A, B, C);

答案 1 :(得分:1)

最好的方法是创建一个名为createSequenceOfFamilies的公共静态方法,该方法由一个整数参数化,表示您想要多少个族。在该方法中,您可以直接设置leftNeighbourrightNeighbour字段。

这样你可以避免使用setter并使你的对象保持不变。

你的电话会像

Family a = Family.createSequenceOfFamilies(3);

然后,您呼叫b的内容为a.getRightNeighbour()c成为b.getRightNeighbour()

答案 2 :(得分:0)

要编译代码,可以执行以下操作:

Family A = null;
Family B = null;
Family C = null;

A = new Family(null, B); 
B = new Family(A, C);
C = new Family(B, null);

但是你仍然需要在某些时候使用setter设置值。因为您无法分配尚未创建的对象。如果你想避免setter,你可以创建另一个包装setter的方法,但是你必须使用它们。