• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Junilu Lacar
  • Knute Snortum
Saloon Keepers:
  • Ron McLeod
  • Ganesh Patekar
  • Tim Moores
  • Pete Letkeman
  • Stephan van Hulst
Bartenders:
  • Carey Brown
  • Tim Holloway
  • Joe Ess

When are good times to use inner class in Java  RSS feed

 
Ranch Hand
Posts: 85
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When are good times to use inner class in Java?
The common usage i see is to implement swing event handling. Is there any example where using inner class can result in cleaner code?
 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
One best use of inner classes is writing Comparators for custom objects.
Inner classes should be used sparingly as its , a kind of security hole.
 
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When you need create a object of a class that implement a interface or extends
a class and only used once,you can use inner class to get cleaner code.
 
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

one of the typical situations where an inner class seems to be appropriate to me are typical factories (Factory Method, Abstract Factory or Builder pattern). By making the class which implements the exposed interface a private inner one (usually static), it is ensured that the one objective of the corresponding pattern is accomplished: To encapsulate instance control.

If the implementing class were a package-private outer class, then this kind of control would be broken at the package level already: Other classes might instantiate it directly using its constructor, and the factory (see above) does not have the option to change the time, quantity and means at which the class is being instantiated later.

Example:

(Simplified. A static method that takes parameters is not good in most cases. See the ButtonFactoryCreator in my Design Principles article for a better solution.)

Generally, a private inner class (static or not; see "Effective Java" (Bloch) for the decision between static member classes, nonstatic member classes, anonymous classes and local classes) is used to encapsulate at the appropriate level in certain situations.

I think that there are not many situations in which a public inner class, static or not, is a good design choice.

Kai
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!