Inner Classes in Java
Understanding Types, Access,
Casting, and Examples
Types of Inner Classes
• 1. Static Nested Class
• 2. Non-Static Inner Class
• 3. Local Inner Class
• 4. Anonymous Inner Class
1. Static Nested Class
• Defined as a static member of the outer class.
• Can only access static members of the outer class directly.
• Access Specifiers: Can be private, protected, or public.
• Casting: Useful for simpler access without outer instance.
Example:
class OuterClass {
static String outerStatic = "Static Outer Field";
static class StaticNestedClass {
void display() {
System.out.println(outerStatic);
}
}
}
2. Non-Static Inner Class
• Tied to an instance of the outer class.
• Can access both static and non-static members of the outer class.
• Access Specifiers: Can be private, protected, or public.
• Casting: Useful for accessing outer class instances and downcasting.
Example:
class OuterClass {
String outerField = "Outer Field";
class InnerClass {
void display() {
System.out.println(outerField);
}
}
}
3. Local Inner Class
• Defined within a method, accessible only within that method.
• Can access final or effectively final variables of the method.
• Access Specifiers: Cannot have access specifiers.
Example:
class OuterClass {
void outerMethod() {
int localVar = 5;
class LocalInnerClass {
void display() {
System.out.println(localVar);
}
}
LocalInnerClass localInner = new LocalInnerClass();
localInner.display();
}
}
4. Anonymous Inner Class
• No name, often used to implement interfaces or abstract classes.
• Defined and instantiated in one expression.
• Access Specifiers: No explicit access specifiers.
Example:
interface Greeting {
void sayHello();
}
public class Example {
public static void main(String[] args) {
Greeting greeting = new Greeting() {
public void sayHello() {
System.out.println("Hello");
}
};
greeting.sayHello();
}
}
Casting in Inner Classes
• Upcasting: Casting a derived class reference to its superclass.
- Generalize functionality, refer to an inner class through
interface/superclass.
• Downcasting: Casting superclass reference back to derived class type.
- Access specialized methods in subclass; cautious due to
ClassCastException.
Example:
OuterClass.InnerClass inner = outer.new InnerClass();
Object obj = inner; // Upcasting
OuterClass.InnerClass downCasted = (OuterClass.InnerClass) obj;
// Downcasting
When to Use Each Type
• Static Nested Class: For static utility classes
within the outer class.
• Non-Static Inner Class: When access to outer
class’s instance members is needed.
• Local Inner Class: Good for encapsulating
complex, one-time logic within a method.
• Anonymous Inner Class: For concise
implementations of interfaces or abstract classes.