Inner Classes In Java – Static, Non Static, Method Inner and Anonymous Classes

Inner Classes In Java – Static, Non Static, Method Inner and Anonymous Classes

What are inner classes?
A class which is defined within another class is the inner class.

What is the use of inner class?
The  inner class is mainly used as logically grouping classes at one place.If you have a class and that class is used only by one other class, then we can group the first class within another class.

There are two types of Inner class,

  • Static Nested Class
  • Non Static Nested Class
    • Method Local
    • Anonymous Inner Class

Static Nested vs Non-Static Nested Class:
Static Nested Class cannot access outer class variables and methods, where as Non Static nested class have full access to outer class variables and methods.


Static Nested Class:

Static class declared within the outer class.

To access the static inner class,
outerclass.innerclass innerclass = new outerclass.innerclass()

Output:

Non Static Nested Class:

Non Static class declared within the outer class.

outerclass.innerclass innerclass = new outerclass.innerclass()

Output:

Method Local Inner Class:

A class declared within a method and create object and call method within the same method.

Output:

Anonymous Nested Class:

In Anonymous inner class, we use the interface as nested class.

Interface cannot be initialized, so how are we using new keyword?

If we look through the code, we use new keyword for interface but we are not actually creating an object. We use new and implement the interface method and close the curly braces with colon.

Output:

Read More