File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes What is a practical example of a nested static class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "What is a practical example of a nested static class" Watch "What is a practical example of a nested static class" New topic
Author

What is a practical example of a nested static class

Hemal Mehta
Ranch Hand

Joined: Nov 16, 2000
Posts: 101
Where would it be useful? Could someone give an example as to it's practical application?
Peter den Haan
author
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: What is a practical example of a nested static class