This week's book giveaway is in the General Computing forum. We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line! See this thread for details.
Hi all I am a newbie to both javaranch and java. I was reading up on nested static classes.Is there a good rule of thumb when you would want to include them in your program design.Are there some obvious scenarios which call for using them.
One reason you may nest is that the class represents a subordinate concept:
Here Link is only useful in the presence of LinkedList.
A second reason is hiding: you can make the nested class private, an access level that top-level classes can't enjoy (because it makes no sense for them!) Again in this example, making Link private makes it an implementation detail of LinkedList, hidden from other classes outside of LinkedList.
This second reason is less compelling to me, because you can give top-level classes default level access and then they'll be inaccessible to classes outside this package, which is usually sufficient, as far as hiding implementation details goes.
A third reason is that nested classes can access private members of outer classes. In C++, they have a saying: friends can touch your private parts:
This is justified because one thinks of Link as being part of LinkedList's implementation, and one part of an implementation always has access to all the other parts.
I find I do use this feature often, but for inner classes -- non-static -- versus static nested classes. I think that's because my few nested static classes tend to be of the simple, Link, variety.