This week's book giveaway is in the Testing forum. We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line! See this thread for details.
yes they are used and yes they are acceptable. But care should be taken to not overuse them, as they can make for messy code.
Basically an inner class should have no meaning outside the class it's in. For example I've a few servlets that create a thread to do some long duration database access in the background while the servlet returns the confirmation page telling the database operation has started (errors are logged but not shown to the client in this case as the operation can take several minutes to complete). The thread uses an inner class of the servlet to define its processing (as a Runnable). Outside the servlet that class has no meaning whatsoever (in fact the method that's now the run method was first part of the servlet as a private method).
Another example would be a class returned from a method which can only be instantiated from that method and nowhere else because very specific things are needed that aren't available anywhere else.
Or maybe something very small and very shortlived.
We often create inner classes on the fly in Swing and other places where we need a dead simple implementation of an interface. The syntax is rather fussy, and I try to keep these to one or two lines of code in the method body.
I've made a few inner classes that are really quite private to the outer class, as Jeroen suggested. For example one class holds some data and does some things with it, but has no get method to let anybody else see the data. It uses an inner class to define the data structure and limited behavior. Again, I'd try to keep such a beast very small.
I use an HTML parser that defines parts of the DOM tree as inner classes. The author enforces a rule that I can never get an instance of the inner class without having an instance of the outer class to make it for me. In this case the inner class makes sense "outside" the outer class, but not "without" the outer class. Here's the Quiotix Parser if you'd like to examine their code.
I don't think inner classes are ever necessary. Any of the ones I described above could have been regular classes defined in their own source files. But they don't clutter your source directories, sometimes they are more convenient, sometimes they come with useful rules of visibility, so we still use them.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Outer and Inner classes form a fundamental part of any java program ,they promote encapsulation if you declare a class in your programm it either is TOP Level class or is an outer or inner class. There are varoius advantages of using inner classes to outer and Vice-Versa