freetimestudys@gmail.com          +91-7097633380
  Login Here                        

Nested classes

Declaring the class inside another class is called nested classes. This concept is introduced in the 1.1 version.
The nested classes are two types
Static nested classes:- The nested classes declare as a static modifier is called static nested classes.
   1. Static nested classes
Non static nested classes:- these are called inner classes.
   2. Normal inner classes
  3. Method local inner classes
  4. Anonymous inner classes

Java Images

Uses of nested classes:-

1. It is the way logically grouping classes that are only used in the one place.
If a class is useful to only one other class then it is logically embedded it into that classes make the two classes together.

A is only one time usage in the B class

class A
{
};
class B
{
A a=new A();
};

by using inner classes

class B
{
class A
{
};
};

2. It increase the encapsulation
If we are taking two top level classes A and B the B class need the members of A that members even we are declaring private modifier the B class can access the private numbers moreover the B is not visible for outside the world.
3. It lead the more readability and maintainability of the code
Nesting the classes within the top level classes at that situation placing the code is very closer to the top level class.