Middle
What are the differences between nested classes and inner classes in Java?
sobes.tech AI
Answer from AI
-
Nested classes: Static members of an outer class. They do not have direct access to non-static members (fields and methods) of the outer class, only through an instance of the outer class. Declared with the
statickeyword. -
Inner classes: Non-static members of an outer class. They have full access to all members (static and non-static) of the outer class, including private ones. To create an instance of an inner class, an instance of the outer class is required. They do not use the
statickeyword.
Example:
// Outer class
class Outer {
private int outerField = 10;
private static int staticOuterField = 20;
// Static nested class
static class StaticNestedClass {
void display() {
// Access only static members of the outer class
System.out.println("Static nested: " + staticOuterField);
// No direct access to outerField
// System.out.println(outerField); // Compilation error
}
}
// Non-static inner class
class InnerClass {
void display() {
// Access to all members of the outer class
System.out.println("Inner: " + outerField);
System.out.println("Inner (static): " + staticOuterField);
}
}
}
// Usage
public class Main {
public static void main(String[] args) {
// Creating an instance of the static nested class
Outer.StaticNestedClass staticNested = new Outer.StaticNestedClass();
staticNested.display();
// Creating an instance of the inner class requires an instance of the outer class
Outer outer = new Outer();
Outer.InnerClass inner = outer.new InnerClass();
inner.display();
}
}
| Feature | Nested Class | Inner Class |
|---|---|---|
| Keyword | static |
No |
| Access to outer class members | Only static | All |
| Requires an instance of the outer class to create an instance | No | Yes |
| Connection with an instance of the outer class | No | Yes |