Junior — Middle
What is the difference between an inner class and a nested class in programming?
sobes.tech AI
Answer from AI
In Java (and in Android), a nested class is any class declared within another class. Nested classes are of two types:
- Static nested class — declared with the
staticmodifier. It does not have direct access to the non-static members of the outer class. - Inner class — a nested class without the
staticmodifier. It is associated with an instance of the outer class and has access to its non-static fields and methods.
Example:
class Outer {
private int outerField = 10;
static class StaticNested {
void print() {
// Cannot access outerField directly
System.out.println("Static nested class");
}
}
class Inner {
void print() {
// Can access outerField
System.out.println("Inner class, outerField = " + outerField);
}
}
}
Thus, the main difference is that the inner class is associated with an instance of the outer class and can access its non-static members, while the static nested class is not.