When to user inner classes in java - I know one place event listener but except that where? [duplicate]
Possible Duplicate:
Usage of inner class
When to user inner classes in jav开发者_如何学Pythona - I know one place event listener but except that where ? What are pro- cons of using it ?
its same as When to use inner classes?
In general I would use inner classes when you need a one-off implementation of an interface or abstract class which doesn't need to be repeated. Event Listeners may be one good example of this.
At the moment I am working on a an application which uses Google Web Toolkit which relies heavily on inner classes as closures.
The pros of using inner classes are that you don't have to define a whole new class, you can just use them inline as and when you need them.
The cons are that:
- You can't really re-use them in other places, i.e. an inner class may be better served by creating a more generic standard class and re-using it.
- You can't define other methods inside an inner class and call them from outside the inner class.
From a design perspective when you to implement Composition in java you use inner classes.
In composition, the lifetime of the contained objects are managed by parent and the child type doesent make any sense outside the parent itself. For e.g. Entry(node) inner class in LinkedList.
精彩评论