Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can two objects contain one another in Java?

Tags:

java

object

oop

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?

like image 963
Mason Avatar asked May 17 '26 04:05

Mason


2 Answers

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).

like image 147
Edwin Buck Avatar answered May 19 '26 16:05

Edwin Buck


There are no problems. Cycles are allowed. You should have just compiled and checked rather than asking a question ;-).

like image 34
Aravind Yarram Avatar answered May 19 '26 16:05

Aravind Yarram