In Java, an inner class is a class defined within another class. Inner classes have several types and serve different purposes. Here's an overview of the types of inner classes in Java:
Nested Inner Class (Non-static Inner Class):
- Defined within another class without using the
static
keyword. - Has access to the enclosing class's instance variables and methods, even private ones.
- Can be instantiated only within the enclosing class or within other nested classes of the enclosing class.
- Example:java
class OuterClass { private int outerField; class InnerClass { void display() { System.out.println("Outer field: " + outerField); } } }
- Defined within another class without using the
Static Nested Class:
- Defined within another class using the
static
keyword. - Operates like a regular top-level class, but is nested for packaging convenience.
- Cannot directly access instance variables and methods of the enclosing class unless through an object reference.
- Example:java
class OuterClass { private static int outerStaticField; static class StaticNestedClass { void display() { System.out.println("Outer static field: " + outerStaticField); } } }
- Defined within another class using the
Local Inner Class:
- Defined within a method or scope block (like a local variable).
- Has access to the variables and parameters of the enclosing method (or scope) if they are
final
or effectively final. - Exists only for the duration of the method call.
- Example:java
class OuterClass { void outerMethod() { final int localVar = 10; class LocalInnerClass { void display() { System.out.println("Local variable: " + localVar); } } LocalInnerClass inner = new LocalInnerClass(); inner.display(); } }
Anonymous Inner Class:
- A local inner class without a name, defined and instantiated simultaneously.
- Often used for event handling or implementing interfaces with a short, one-time use.
- Example:java
interface Greeting { void greet(); } class OuterClass { void displayGreeting() { Greeting greeting = new Greeting() { public void greet() { System.out.println("Hello!"); } }; greeting.greet(); } }
Inner classes provide encapsulation and code organization benefits, especially when a class is closely tied to another and is not needed outside of its enclosing class. They can also improve code readability and maintainability by grouping related code together.