Here's the situation. Let's say we have two separate object types, and we want each of them to point to the other. For example:
public class Object1
{
Object2 obj2;
public Object1(Object2 obj)
{
obj2 = obj;
}
}
public class Object2
{
Object1 obj1;
public Object2()
{
obj1 = null;
}
public void setObject1(Object1 obj)
{
this.obj1 = obj;
}
}
public class Tester
{
public static void main(String[] args)
{
Object2 obj2 = new Object2();
Object1 obj1 = new Object1(obj2);
obj2.setObject1(obj1);
}
}
Is this allowed in Java? Are there any problems with doing something like this?
Yes, it is allowed in Java. The compiler tracks dependencies in a manner slightly different than C / C++ compilers, so when it detects that you compiled Object1 which needs to use a non-compiled version of Object2, it will also compile Object2.
As far as the meaning of "contains" in this context, to be technically correct, neither object contains the other, they both contain references to the other. That said, there is no limitation on objects containing references (no matter how circular).
Of interesting note, the garbage collector also deals with circular references nicely, so if a disconnected circle of referencing objects is created, they will get garbage collected at roughly the same time. Older techniques of garbage collection that work through reference counting could be fooled by circular references, but Java uses a reachability algorithm which determines if the objects are reachable from the main program thread(s).
There are no problems. Cycles are allowed. You should have just compiled and checked rather than asking a question ;-).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With