In Java, an inner class is a class defined within another class. Inner classes have access to the members of the enclosing class, including private members. They provide a way to logically group classes and increase encapsulation, as well as facilitate better code organization and readability. There are several types of inner classes in Java:
A nested inner class is defined within another class and can access the members (including private) of the enclosing class. It can be static or non-static.
Example of a non-static nested inner class:
public class Outer { private int outerField; class Inner { void display() { System.out.println("Value of outerField: " + outerField); } } public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display(); // Output: Value of outerField: 0 } }
A static nested class is a static member of the enclosing class and does not have access to the instance members of the enclosing class. It is typically used for grouping classes together.
Example of a static nested class:
public class Outer { static class Nested { void display() { System.out.println("Inside static nested class"); } } public static void main(String[] args) { Outer.Nested nested = new Outer.Nested(); nested.display(); // Output: Inside static nested class } }
A local inner class is defined within a block of code, typically within a method. It has access to the members of the enclosing block and can access local variables if they are declared final or effectively final.
Example of a local inner class:
public class Outer { void display() { int localVar = 10; class LocalInner { void innerDisplay() { System.out.println("Value of localVar: " + localVar); } } LocalInner inner = new LocalInner(); inner.innerDisplay(); // Output: Value of localVar: 10 } public static void main(String[] args) { Outer outer = new Outer(); outer.display(); } }
An anonymous inner class is a class without a name that is defined and instantiated at the same time. It is typically used for overriding methods of a class or interface.
Example of an anonymous inner class:
public class Outer { void display() { Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Inside anonymous inner class"); } }; Thread thread = new Thread(runnable); thread.start(); // Output: Inside anonymous inner class } public static void main(String[] args) { Outer outer = new Outer(); outer.display(); } }