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?
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 B
s 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.