Java Inner Classes
In Java, an inner class is a class defined within another class. Inner classes are primarily used for
grouping closely related classes together, increasing encapsulation, and improving code
organization. There are several types of inner classes in Java, each serving different purposes:
1. Member Inner Class
This is the most common type of inner class. It's defined at the member level of a class and can
access all members (fields and methods) of the outer class, including private members.
Example:
OuterClass {
int x = 10;
class InnerClass {
int y = 5;
}
}
public class Main {
public static void main(String[] args) {
OuterClass myOuter = new OuterClass();
OuterClass.InnerClass myInner = myOuter.new
InnerClass();
System.out.println(myInner.y + myOuter.x);
}
}
2. Static Nested Class
This type of class is declared with the static keyword. It can access only static members of
the outer class. Static nested classes are essentially similar to a regular class but are nested
for packaging convenience.
Example
public class Outer {
private static int staticOuterField;
public static class Nested {
public void display() {
System.out.println("Static outer field: " +
staticOuterField);
}
}
}
3. Local Inner Class
These classes are defined within a block of code, typically within a method body. They have
access to the members of the enclosing class and can also access local variables of the enclosing
method, but these local variables must be effectively final or explicitly declared final.
Example:
public class Outer {
private int outerVar;
public void display() {
int localVar = 10;
class LocalInner {
public void display() {
System.out.println("OuterVar: " +
outerVar);
System.out.println("Local variable: " +
localVar);
}
}
LocalInner inner = new LocalInner();
inner.display();
}
4. Anonymous Inner Class
These are declared and instantiated at the same time. They don't have a name and are
typically used for implementing interfaces or extending classes in a concise way.
public class Outer {
public void display() {
Runnable r = new Runnable() {
@Override
public void run() {
System.out.println("Running...");
}
};
Thread t = new Thread(r);
t.start();
}
}