An inner class is said to be a member of the outer class. Does that mean that whenever an object of the outer class is created, an instance of inner class is also created implicitly?
3 Answers
No. An instance of the inner class is created only when you instantiate it.
Note that the constructor of the inner class requires an instance of the outer class (although this is masked by the compiler). This is true for non-static nested classes. Static nested classes can be instantiated without a parent instance (since they are static)
5 Comments
aps
But are static inner classes used in real life?
Bozho
yes, a lot. Even more than non-static I might say (though I don't have figures)
aps
@Bozho oh i didn't know that...actually i had read somewhere that usually non static nested classes, called inner classes are mostly used...not the static ones... but the 112K beside your name is too much to not take your word for it...thanks anyway...
Bozho
the 112k doesn't have much to do with that particular question :) I am not entirely sure which ones are used most, I just feel I've seen more static ones than non-static, but I may be as well wrong if a statistical analysis is made.
Inquisitive
@Bozho the correct terminology is static nested class. There isn't anything called as static inner class.
There are different types of inner classes each acting differently.
- Static member classes
- Member classes
- Local classes
- Anonymous classes
You can find a good overview of all of them here : http://www.javaworld.com/javaworld/javaqa/2000-03/02-qa-innerclass.html