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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
class OuterClass { private String message = "Hello from Outer Class!"; class InnerClass { void display() { System.out.println(message); } } public static void main(String[] args) { OuterClass outer = new OuterClass(); OuterClass.InnerClass inner = outer.new InnerClass(); inner.display(); } } //Output: Hello from 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
class OuterClass { static String greeting = "Hello from Static Nested Class!"; static class NestedStaticClass { void display() { System.out.println(greeting); } } public static void main(String[] args) { OuterClass.NestedStaticClass nested = new OuterClass.NestedStaticClass(); nested.display(); } } //Output: Hello from Static Nested Class! |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class OuterClass { void outerMethod() { class LocalInnerClass { void display() { System.out.println("Hello from Local Inner Class!"); } } LocalInnerClass local = new LocalInnerClass(); local.display(); } public static void main(String[] args) { OuterClass outer = new OuterClass(); outer.outerMethod(); } } //Output: Hello from Local Inner Class! |
- 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
abstract class Animal { abstract void makeSound(); } public class AnonymousInnerClassExample { public static void main(String[] args) { Animal cat = new Animal() { void makeSound() { System.out.println("Meow! Meow!"); } }; cat.makeSound(); } } //Output: Meow! Meow! |
- No explicit class name.
- Used for implementing interfaces or extending abstract classes.