One common use of inner classes is as ActionListeners for Swing buttons, etc. This way, you can create a separate event handler for each button (or or menu or whatever), but have all of the code in one class (i.e., for the screen). Sometimes this is done with anonymous inner classes as well (i.e., where the inner class is created on the fly and not given a name).
I think this is the least-often-used type of class in Java. At least for me. I don't recall if I've ever had a legitimate use for it, other than to test the concept. I think that when they came up with inner and nested classes, they just got the idea that they might as well let you declare a class anywhere. I suppose I might use a local class if I had a class that was small & simple enough to be an anonymous class, but I needed to use it more than once inside a method. Maybe I need to add a method to an existing class, then use the method. However I'm a big fan of keeping methods short, so it's hard for me to imagine a good example where I would use this. Probably I'd just make the class a member class instead.
"I'm not back." - Bill Harding, Twister
Joined: Jun 03, 2007
Hi Jim. I'm pretty new at Java and OOP, and I'm interested in your opinion. How would you do the mutliple button example? Would you create a separate class for each button? Thanks. Mark Dexter
Joined: Jan 30, 2000
Hi Mark. It occurs to me I may have misinterpreted the question. There are really two types of local classes: named local classes, and anonymous classes. Sun doesn't usually refer to anonymous classes as local classes, but they are - in the sense that they're classes defined locally inside a method (or constructor or initializer). But anonymous classes are shorter and have a different syntax. I interpreted the question as when would you use a named local class. And I usually wouldn't. I would use an anonymous class instead. In your example:
Generally I think that anything short enough to make into a named local class is short enough to make into an anonymous class. And anything too big to be an anonymous class is too big to be a named local class. So I use ananymous classes, and I use nested member classes (static and nonstatic), but I almost never use named local classes.
Joined: Jun 03, 2007
Hi Jim. Thanks for the reply. It makes perfect sense to me. Mark
subject: When would I use a method-local inner class?