Nested class is a class defined inside another class.
Used to logically group classes, improve encapsulation and access outer class members.
Types of Nested Classes
Type | Static? | Can Access Outer Instance? | Common Use Case |
---|---|---|---|
Static Nested | β | β | Utility/helper class |
Inner Class | β | β | tightly coupled object relationships |
Local inner | β | β | Defined inside a method |
Anonymous Class | β | β | One-off overrides (already covered) |
Example
class Outer {
static class Inner {
void show() {
System.out.println("Static Nested");
}
}
}
Outer.Inner obj = new Outer.Inner();
obj.show();
class Outer {
class Inner {
void show() {
System.out.println("Inner Class");
}
}
}
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.show();
class Outer {
void display() {
class Local {
void msg() {
System.out.println("Local Inner Class");
}
}
Local local = new Local();
local.msg();
}
}
Key Points
- Inner classes can access all members (even private) of the outer class.
- Static nested classes cannot access non-static members directly.
- Helps keep code organized and logically grouped.
Tip
If youβre asked about class organization or encapsulation, mention nested classes as a clean way to group related logic.
Parent: _OOP Advanced Tools