Search code examples
javainfinite-loop

Shouldn't having classes having instances of each other form an infinite loop


I have two classes that make instances of each other, which probably should create an infinite loop, but they're not. class A is created first.

class A {

    B[] b = new B[9];

    A() {
        for (each) { // pseudo code
            b[each] = new B(this);
        }
    } 
}
class B {

    A a;

    B(A a) {
        this.a = a;
    } 
}

My Question: Why is this code NOT making an infinite loop?


Solution

  • You only have one A instance (if you write new A() somewhere) that holds 9 B instances and each of them hold a reference to the same A instance.

    This creates a loop in the sense that the memory of A and the Bs cannot be freed because they reference each other. Other than that there is no problem, no "infinite" loop that would cause any major problems, in particular there is no infinite loop creating more and more objects.

    If you wrote

    class B {
    
        A a;
    
        B() {
            this.a = new A();
        } 
    }
    

    then you would get into trouble.