• Post Reply Bookmark Topic Watch Topic
  • New Topic

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

 
ying lam
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?
 
rohan sans
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.
 
Lucas Lee
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.
 
Kai Witte
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
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!