Why is it legal in Java to declare an object of the enclosing class inside the nested class? It cannot be meaningful as enclosing class is not completely defined at the time of the declaration of its object.Furthermore, if A is the enclosing class and B is the nested class, then an object of class A will also include members of class B, which again includes an object of class A, and this would go on indefinitely. My understanding is that since the enclosing class cannot access members of the nested class, so an object of the former can access only the members which are not in the nested class, which resolves this problem. Is that correct, or is there something else going on?
It cannot be meaningful as enclosing class is not completely defined at the time of the declaration of its object.
So what? If I follow your logic, it cannot be meaningful within a method of a class to declare an object of the enclosing class either, for the very same reason.
It seems that you misunderstand the difference between compile and run time. When the source code is parsed in order to be compiled, and the tokenizer processes
B, then, indeed,
A may not be completely defined yet. In a similar way, when
A contains a method
hello() which calls
world(), the tokenizer may process the first method while the second one doesn't exist yet.
At run time, however, both
B exist. You can do Reflection to list their members, and you can call
B without any issue.
My understanding is that since the enclosing class cannot access members of the nested class
It's wrong. Not only the enclosing class can access members of the nested class, but it can even access too much of them, something which is not particularly intuitive in Java.
The goal of nested classes is to be able to create types which make sense only within the parent class. For instance, if the class
A uses temporary data structures when processing some data, and those structures are too specific to the class
A and never used outside of it, creating additional classes which will pollute the namespace is rather unfortunate; instead, put them within the
A class and make them private.