Inner classes in Java


In Java, inner classes are classes defined within another class. They are used to logically group classes that are only used in one place, and they can access members of their outer class (even private ones, depending on type).

Static Inner Classes

Definition:
  • Defined with the static keyword.
  • Does not have access to instance variables/methods of the outer class directly.
  • Acts like a static member of the outer class.
Example:
        
        class Outer {
            static class StaticInner {
                void display() {
                    System.out.println("Inside static inner class.");
                }
            }
        }

        public class Main {
            public static void main(String[] args) {
                Outer.StaticInner obj = new Outer.StaticInner();
                obj.display();
            }
        }
        
        
Use Case:
  • When the inner class does not need access to instance members of the outer class.
  • Useful in utility/helper classes.

Anonymous Inner Classes

Definition:
  • A class without a name, defined and instantiated in a single expression.
  • Typically used to extend a class or implement an interface once.
Example:
        
        abstract class Animal {
            abstract void makeSound();
        }

        public class Main {
            public static void main(String[] args) {
                Animal dog = new Animal() {
                    void makeSound() {
                        System.out.println("Woof!");
                    }
                };
                dog.makeSound();
            }
        }
        
        
Use Case:
  • Quick implementation of an interface or abstract class.
  • Ideal for event handling or callbacks (e.g., GUI frameworks, threads).

Local Inner Classes

Definition:
  • Defined inside a method.
  • Can access final or effectively final variables of the enclosing method.
  • Cannot be static.
Example:
        
        public class Outer {
            void outerMethod() {
                int num = 100; // effectively final

                class LocalInner {
                    void print() {
                        System.out.println("Number: " + num);
                    }
                }

                LocalInner inner = new LocalInner();
                inner.print();
            }
        }
        
        
Use Case:
  • When a class is only needed within a specific method.
  • Helps in logically grouping code that’s only used in one place.
Summary Table
Type Scope Can access outer members? Static? Use Case
Static Inner Class Class level Only static members Yes Utility classes, nested helpers
Anonymous Class Inline (expression level) Yes No Event handlers, quick implementations
Local Inner Class Inside a method Yes (final/effectively final vars) No Encapsulating logic within methods