- It is a way of logically grouping classes that are only used in one place.
- It increases encapsulation.
- Nested classes can lead to more readable and maintainable code.
Increased encapsulation—Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared
private. By hiding class B within class A, A's members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
More readable, maintainable code—Nesting small classes within top-level classes places the code closer to where it is used.
As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class — it can use them only through an object reference.
Instance inner class
An anonymous inner class can come useful when making an instance of an object which certain "extras" such as overloading methods, without having to actually subclass a class. In below example we are using Thread using anonymous inner class.