Friday, March 30, 2007

Java :: Static Inner Classes

We all know that Java supports the creation of inner classes. Some people intentionally avoid creating inner classes for many good reasons. And also, one should avoid creating non-static inner classes without a very solid reason. Till now I have never created a non-static inner class except for the anonymous inner classes that I created for event-listeners in GUI programming.

But recently I started using static-inner classes for various purposes and it has tremendously improved my code's readability. Currently I'm using it for two purposes.
  1. Creating Private Utilities
  2. Creating Private Implementations
Creating Private Utilities

What do I mean by "Private Utilities"? We have classes like SwingUtilities, Math, etc. They all contain only "public static" methods and they enforce non instantiability by means of a private constructor. These are public utility classes, but not all the utility classes we create must be public. There are times you will need to have them private. For example, you want to implement your own FileFilter but you don't want to make it public or even package-private. And you also don't want to create that implementation as an anonymous inner class because you think it may clutter the code.

This is a perfect reason for creating a "private static" inner class.

Creating Private Implementations

Just open the source code of java.util.Hashtable and you will see 2 private static inner classes: EmptyEnumerator, and EmptyIterator. When we invoke Hashtable.keys() method, it first checks if the Hashtable has any elements in it. If the number of elements in the Hashtable is 0, it returns an instance of EmptyEnumeration which is a private implementation of java.util.Enumeration interface for empty Hashtable.

These are only a very few applications of static inner classes. I see them as a tool that can make my code more readable, elegant and efficient.

3 comments:

JP said...

Srikant,

Agree with you completly.

100% it improves readability and enhances encapsulation.

Thanks
prashant

Anonymous said...

I am one of those people, who avoid the use of inner classes intentionally for the sole purpose, that they pretty much always hurt code clarity, especially if used in actionlistener methods (that is IMHO the worst kind of use imaginable).

I also did a performance test for this kind of thing and was disappointed by inner classes even further:

http://www.onyxbits.de/content/blog/patrick/design-pattern-menubars-performance-test

Srikanth said...

Patrick,

Your post was interesting; I never thought about performance of inner classes. I also liked your post on the design pattern for Menubars. I'll pass it on to my friends who use Java Swing; they'll be very interested.

Post a Comment