Don Warren Don Warren - 7 months ago 13
Java Question

java two final instances with reference to each other

I have two classes:

public class Group {
private final MyObject object;

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


public class MyObject {
public Group group;

public MyObject () {

}
}


Currently, Group has a final instance of MyObject.

And I initiate them currently like this:

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

object.group = group;


However this is not what I want, since the "group" variable in "MyObject" needs to be final too (for clarity of code and easier debugging).

Is there a way I can somehow do this?

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


Where the modified constructor of "MyObject" would be as such:

public class MyObject {
private final Group group;

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


Thanks in advance

Answer

The only way you can do this is in one of the constructors. In general you want to avoid passing this from a constructor, but in this cases there is no alternative (except a non-final field)

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.