Java
Nested Classes
Explore inner classes, static nested classes, local classes, and anonymous classes in Java.
By TechCoder TeamLast updated: 2026-06-02
In a Nutshell
Explore inner classes, static nested classes, local classes, and anonymous classes in Java. This hands-on tutorial focuses on practical implementation of nested classes concepts.
Nested Classes
A class defined within another class is called a Nested Class.
Types of Nested Classes
1. Static Nested Class
A static class inside another class.
class Outer {
static class StaticNested {
void display() {
System.out.println("Static nested class");
}
}
}
// Usage
Outer.StaticNested obj = new Outer.StaticNested();
obj.display();
2. Inner Class (Non-static)
Requires an instance of the outer class.
class Outer {
class Inner {
void display() {
System.out.println("Inner class");
}
}
}
// Usage
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display();
3. Local Class
Defined inside a method.
class Outer {
void myMethod() {
class Local {
void display() {
System.out.println("Local class");
}
}
Local local = new Local();
local.display();
}
}
4. Anonymous Class
A class without a name, often used for one-time implementations.
interface Greeting {
void sayHello();
}
Greeting greeting = new Greeting() {
public void sayHello() {
System.out.println("Hello from anonymous class!");
}
};
greeting.sayHello();
When to Use Nested Classes?
| Type | Use Case |
|---|---|
| Static Nested | Logically group classes, doesn't need outer instance |
| Inner | Needs access to outer class instance variables |
| Local | Temporary class needed only in one method |
| Anonymous | One-time implementation (event handlers, callbacks) |
AI Mentor
Confused about "Java nested classes types and usage patterns"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3Can a static nested class access instance variables of the outer class?
Yes
No