A nested class is a class declared inside another class.
class Outer {
class Inner {
}
}
Here, Inner is a nested class inside Outer.
Java has four types of nested classes:
Nested Classes
│
├── Static Nested Class
├── Inner Class
├── Local Class
└── Anonymous Class
A nested class declared with static.
class Outer {
static class Inner {
void show() {
System.out.println("Hello");
}
}
}
Create it without creating an Outer object:
Outer.Inner obj = new Outer.Inner();
Static nested class → Does not require an outer class object.
A non-static nested class is called an inner class.
class Outer {
class Inner {
void show() {
System.out.println("Hello");
}
}
}
To create it, you need an object of the outer class:
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
An inner class can access members of its outer object, including private members.
class Outer {
private int value = 10;
class Inner {
void show() {
System.out.println(value);
}
}
}