Saturday, September 01, 2007

When to use inner class


This is a question from a friend of mind.



In a class, we use private fields and private methods to hide, or encapsulate logic from outside. However, sometimes, we need a full functioning class within another class, but the class inside should not in anyway accessible or even exist outside the bigger class. This is the situation we need a inner class.



For example, inside a watch, there are many gears. As a user of a watch, you never care how the gears work within the watch. You even don't care if a watch is work on gears or not (it maybe a electronic watch). In this case, gear could be a inner class in a watch.



Private inner class provides better shielding of complicated logic within a class. The most common case of using an inner class is implementing Listeners inside another class. You just use an anonymous inner class that implements a specific Listener interface.



Although you can also define an inner class as a public class, but usually I do not recommend programmers to do this. Because you can always extract public inner class as an ordinary public class. I think it make no sense to use a public inner class unless you want to do something dirty.