Nested and Inner Classes in Java
Nested and Inner Classes in Java
1. Nested Classes:
A nested class is a class defined within another class. In Java, nested classes are used to logically
group classes that are only used in one place. They increase encapsulation and can lead to more
readable and maintainable code.
Types of Nested Classes:
Static Nested Class:
o It is declared with the static keyword.
o Since it's static, it can access the outer class's static members, but not non-static
members directly.
o It does not require an instance of the outer class to be instantiated.
o Example:
class OuterClass {
static int outerStaticVar = 10;
class InnerClass {
void display() {
System.out.println("Outer variable: " + outerVar);
}
}
}