Sobes.tech
Junior — Middle

What is the difference between a nested class declared as static and an inner class without a modifier in Java?

sobes.tech AI

Answer from AI

In Java, there are two types of nested classes: static nested classes and inner classes (which are not declared as static).

  • Static nested class:

    • Declared with the static modifier inside the outer class.
    • Does not have direct access to non-static fields and methods of the outer class.
    • An instance of a static nested class is not associated with an instance of the outer class.
    • Used like a regular class but logically grouped with the outer class.
  • Inner class (non-static):

    • Not declared as static.
    • Has access to all fields and methods of the outer class, including private ones.
    • An instance of an inner class is associated with an instance of the outer class.
    • To create an inner class instance, an object of the outer class is required.

Example:

public 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() {
            // Access to outerField
            System.out.println("Inner class, outerField = " + outerField);
        }
    }
}

// Usage:
Outer.StaticNested staticNested = new Outer.StaticNested();
staticNested.print();

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.print();

Thus, the main difference is the connection to an instance of the outer class and access to its non-static members.

What is the difference between a nested class… - sobes.tech