java两个最终实例互相引用

时间:2016-05-02 08:31:51

标签: java

我有两个班级:

public class Group {
  private final MyObject object;

  public Group(MyObject object) {
    this.object = object;
  }
}


public class MyObject {
  public Group group;

  public MyObject () {

  }
}

目前,Group有一个MyObject的最终实例。

我现在就这样发起他们:

MyObject object = new MyObject();
Group group = new Group(object);

object.group = group;

然而,这不是我想要的,因为"组" " MyObject"中的变量也需要是最终的(为了清晰的代码和更容易的调试)。

我有办法以某种方式这样做吗?

MyObject object = new MyObject(group);
Group group = new Group(object);

修改后的构造函数" MyObject"就是这样:

public class MyObject {
  private final Group group;

  public MyObject (Group group) {
    this.group = group;
  }
}

提前致谢

1 个答案:

答案 0 :(得分:1)

唯一可以做到这一点的方法是在其中一个构造函数中。通常,您希望避免从构造函数传递this,但在这种情况下没有其他选择(非最终字段除外)

public class Group {
  private final MyObject card;

  public Group(MyObject card) {
      this.card = card;
  }
}


public class MyObject {
  private final Group group;

  public MyObject () {
     // initialise MyObject

     // do this only after initialising MyObject
     group = new Group(this);
  }
}

// to create both at once.
MyObject obj = new MyObject(); // will have a Group inside.