Inner Classes in Java

 Inner Classes in Java:

 Java supports four types of inner classes:

  1. Non-static Inner Class: Associated with an instance of the outer class and can access its members directly.
    1. non-static inner class (also called a regular inner class) is a class defined inside another class without the static keyword. It has access to the instance variables and methods of the outer class.
    2. Example:


  2. Static Nested Class: Similar to static methods; it does not require an instance of the outer class and can only access static members.
    1. static nested class is a class defined inside another class using the static keyword. Unlike a non-static inner class, it does not require an instance of the outer class to be created. It behaves like a normal top-level class but is scoped inside the outer class.
    2. Example:


  3. Method-local Inner Class: Defined within a method and can access local variables and parameters of the method if they are final or effectively final.
    1. method-local inner class is a class defined inside a method of an outer class. It is created and used only within that method’s scope, similar to how a local variable behaves.
    2. Example:


  4. Anonymous Inner Class: A class defined without a name at the time of instantiation. It is often used to provide aone-time implementation of an interface or a subclass.
    1. An anonymous inner class in Java is a class without a name that is declared and instantiated in a single statement. It is mainly used when you need a one-time implementation of an interface, an abstract class, or even a concrete class.
    2. Example:




Quick Summary (Cheat Sheet- Which to use)

  • Non-static Inner Class → When it needs outer instance (tight coupling).

  • Static Nested Class → When it doesn’t need outer instance (looser coupling).

  • Method-local Inner Class → For temporary helper logic inside a method.

  • Anonymous Inner Class → For one-time use implementations (callbacks, threads, listeners).

Comments