Inner Class

An inner class is a class declared inside another class. It has access to the members (even private ones) of the outer class. This makes it useful for logically grouping related functionality.

  • Helps logically group classes that are only used in one place.
  • Provides better encapsulation by restricting access.
  • Can access private members of the outer class.

Types of Inner Classes

Java provides four types of inner classes:

  • Member Inner Class
  • Static Nested Class
  • Local Inner Class
  • Anonymous Inner Class

Member Inner Class

A member inner class is a non-static class defined within another class. It can access all members (including private) of the outer class.

  • You need an instance of the outer class to create an inner class object.
  • The inner class can access private members of the outer class.

Static Nested Class

A static nested class is a static class inside another class. It cannot access non-static members of the outer class directly.

  • It is declared with the static keyword.
  • Does not need an instance of the outer class to create an object.
  • Cannot access non-static members of the outer class.

Local Inner Class

A local inner class is defined within a method and can only be used inside that method.

  • Defined inside a method.
  • Can only be instantiated within the method.

Anonymous Inner Class

An anonymous inner class is an unnamed class used when you need a one-time implementation of a class or interface.

  • No explicit class name.
  • Used for implementing interfaces or extending abstract classes.