2 Years
Discussion Span
Last Post by JamesCherrill

An nested class has access to the variables and methods of its enclosing class, and it can be private to the enclosing class. That's a completely different kind of sharing and encapsulation compared to a separate class. Which you chose depends on what you need.
Consider a Listener class in Swing. You want it to have access to the components of the GUI, but you don't want anyone lese messing with it.

Oracle has a good tutorial on this subject right here


Most situations call for an ordinary class.
Nested classes are good for event listeners, and for little data structures used inside a class, eg Linked List classes may have an inner Entry class that encapsulates the data and the link. Just ask the two questions:
Is this class needed outside the main class?
Does this class need access to the main class's variables?

Edited by JamesCherrill

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.