1

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?

3

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 A and B exist. You can do Reflection to list their members, and you can call B from A and A from 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.