Inner classes in Java are classes defined within the body of another class. They are used to logically group classes that are only used in one place, which can increase encapsulation and readability. There are several types of inner classes:
-
Non-static Inner Class:
- This type of inner class is associated with an instance of the outer class. It can access the outer class's members (including private members) directly.
- Example:
class OuterClass { private String outerField = "Outer Field"; class InnerClass { void display() { System.out.println(outerField); // Accessing outer class field } } }
-
Static Inner Class:
- A static inner class does not have access to instance variables or methods of the outer class. It can only access static members of the outer class.
- Example:
class OuterClass { static String staticOuterField = "Static Outer Field"; static class StaticInnerClass { void display() { System.out.println(staticOuterField); // Accessing static outer class field } } }
-
Method-local Inner Class:
- This type of inner class is defined within a method of the outer class. It can access local variables of the method (if they are final or effectively final) and the outer class's members.
- Example:
class OuterClass { void outerMethod() { class MethodLocalInnerClass { void display() { System.out.println("Inside Method Local Inner Class"); } } MethodLocalInnerClass inner = new MethodLocalInnerClass(); inner.display(); } }
-
Anonymous Inner Class:
- An anonymous inner class is a class without a name that is defined and instantiated in a single expression. It is often used to implement interfaces or extend classes on the fly.
- Example:
interface Greeting { void greet(); } class OuterClass { void createGreeting() { Greeting greeting = new Greeting() { public void greet() { System.out.println("Hello from Anonymous Inner Class!"); } }; greeting.greet(); } }
Inner classes provide a way to logically group classes and can help in organizing code, especially when the inner class is closely related to the outer class.
