Ernest Friedman-Hill wrote:Hi Marty,
Well as written, neither class actually creates an instance of the other, so it's OK. If each one said something lke
A a = new A();
then yes indeed, it'd be infinite recursion and the program would blow up.
But there is more than one way to end up with a member variable pointing to to an object. For example, consider these two classes:
Here, an instance of A contains an instance of B that refers back to the same "A". If you use "new A()" to create an A object, only two objects are created, one A and one B, and they both know about each other.
Thanks, Ernest,
I think I see my mistake now; I'm still thinking in C++, and forgetting a basic difference, although I'm not certain if I'm right about C++. But I guess that in
Java, you are only creating the reference to the object when you declare it like that, where in C++ you would actually be constructing the object. I realize that's the case, but I need to keep it in mind all the time.
Thanks for the example - that helped me realize my mistake.