• Post Reply Bookmark Topic Watch Topic
  • New Topic

Benefits of inner classes in java  RSS feed

 
Raj Jindal
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the use of creating an inner class ?
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
dividing up internal data (for example for a List internal to a class) without exposing the structure of that data to the outside world.
Another example could be a class that serialises something and reads it back in. By encapsulating it in a class the serialisation operation gets a lot cleaner, by making that an inner class you again prevent exposing that structure to the outside world which has no need to know.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's (almost?) never necessary, but often a handy shortcut. Swing and AWT examples make anonymous listeners this way all the time just because it's quick and convenient and reduces the number of source files.
I use an HTML parser package that has all the DOM node classes inside the parser. That reduces name-space clutter in the package and makes it very explicit where you're getting the class.
Any other good reasons to write em?
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any other good reasons to write em?
Inner classes can access private fields and methods of the enclosing class. If you need a new class that has access to otherwise private data of an existing class, and you don't want to make that data available to the rest of the package (by removing the "private"), you can grant access to one other class by making that class in inner class of the class with the private data or method.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!