Sobes.tech
Junior — Middle

What is the difference between a static nested class and a non-static inner class in Java?

sobes.tech AI

Answer from AI

A static nested class in Java is a class declared within another class with the static modifier. It does not have access to the instance variables and methods of the outer class directly, as it is not associated with an instance of the outer class.

An inner (non-static) class is a class declared within another class without static. It is associated with an instance of the outer class and can directly access its non-static members.

Example:

class Outer {
    private int x = 10;

    static class StaticNested {
        void print() {
            // Cannot access x directly
            System.out.println("Static nested class");
        }
    }

    class Inner {
        void print() {
            // Can access x
            System.out.println("Inner class, x = " + x);
        }
    }
}

Main differences:

  • Static nested class has no reference to an instance of the outer class.
  • Inner class is always associated with an instance of the outer class.
  • To create an inner class, an object of the outer class is needed; for static nested, it is not.
What is the difference between a static nested class… - sobes.tech