I know you can create nested classed (or just classes declared outside of the class in the same file) but what is the point of doing this? Why not just create a new class file?

Recommended Answers

All 3 Replies

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

What are some situations or examples where each are useful in there own way?

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?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.