Sometimes I found someone's codes having nested classes.
When should I create a nested class? Does it make instantiation of the outer class consume more resources?
Thank you in advance.
Sometimes I found someone's codes having nested classes.
When should I create a nested class? Does it make instantiation of the outer class consume more resources?
Thank you in advance.
I think I can see what you're asking.
Suppose you have class A. In Scenerio One this class has no nested class. In Scenerio Two this class has a nested class A.B.
All other things being equal*, the class A will consume no more resources in Scenrio Two than it did in Scenerio One. This is because the two classes A and A.B really are two different classes.
The nesting of classes affects only the scoping of the classes and their members. It does not affect the memory layout of the classes.
*If in Scenerio Two A also contains an instance of an A.B, then not all things would be equal, and class A would be potentially larger than in Scenerio One. But A's member field of type A.B would have to be defined separately from the class definition, so this is a pretty obvious difference.
Does that answer your question?
You can find some good answers here. Use a nested class when it is only used by the enclosing class.
When should I create a nested class?
It depends.
Does it make instantiation of the outer class consume more resources?
It depends.