Junior — Middle
Explain the differences between an inner class and a nested class in Java programming language.
sobes.tech AI
Answer from AI
In Java, the term "nested class" is a general term for all classes declared within another class. Nested classes are divided into 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 non-static nested class that is associated with an instance of the outer class and has access to its non-static fields and methods.
Example:
public class Outer {
private int outerField = 10;
// Inner class
class Inner {
void print() {
System.out.println("Outer field: " + outerField);
}
}
// Static nested class
static class StaticNested {
void print() {
System.out.println("Static nested class does not have direct access to outerField");
}
}
}
Thus, the inner class is associated with an instance of the outer class and can access its non-static members, whereas the static nested class cannot.