Junior — Middle
What is the difference between a static nested class and an inner class in Java?
sobes.tech AI
Answer from AI
A static nested class in Java is a class declared inside another class with the static modifier. It does not have access to the non-static members of the outer class and does not require an instance of the outer class to be created.
An inner (non-static) class is associated with an instance of the outer class and can access its non-static fields and methods. To create an inner class, an object of the outer class is needed.
Example:
class Outer {
int x = 10;
static class StaticNested {
void print() {
System.out.println("Static nested class");
// No access to x
}
}
class Inner {
void print() {
System.out.println("Inner class, x = " + x);
}
}
}
// Usage:
Outer.StaticNested sn = new Outer.StaticNested();
sn.print();
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.print();
Thus, static nested class is more independent of the outer class, while inner class is closely related to an instance of the outer class.