This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is a practical example of a nested static class

 
Hemal Mehta
Ranch Hand
Posts: 101
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Where would it be useful? Could someone give an example as to it's practical application?
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is useful when you've got a class Foo that uses another class Bar, and this class Bar should not be used or cannot be used by any other class but Foo. Making class Bar a default (package-level) access class would enable it to be used by other classes in the package (which you don't want) and just clutter up the package besides.
A good example is the java.util.Collections class. All the wrapper methods (Collections.synchronizedCollection(), Collections.unmodifiableCollection(), etc) return instances of private, static nested classes of java.util.Collections. None of these should be used directly by any class other than Collections itself, and there are enough of them to cause quite a bit of clutter in java.util.
Another (weaker) reason to use static nested classes is to express that two classes are very closely related. Admittedly, they are interfaces rather than classes, but look at java.util.Map and Map.Entry. Making this a nested interface (which is always static) expresses something about the relationship between Entry and Map. It won't surprise you to find that a Map implementation such as HashMap contain a (private) static nested class Entry that implements Map.Entry.
- Peter
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic