Sobes.tech
Junior — Middle

What are the differences between non-static and static inner classes in programming languages?

sobes.tech AI

Answer from AI

In Java, there are two main types of inner classes: non-static (inner classes) and static nested classes. The main differences:

  • Non-static inner classes:

    • Do not have the static modifier.
    • Can access the fields and methods of the outer class, including private ones.
    • To instantiate, an object of the outer class is required.
    • Used when the inner class logically relates to a specific instance of the outer class.
  • Static nested classes:

    • Declared with the static modifier.
    • Do not have a reference to an instance of the outer class.
    • Cannot access non-static fields and methods of the outer class directly.
    • Can be instantiated without an outer class instance.

Example:

class Outer {
    private int outerField = 10;

    class Inner {
        void print() {
            System.out.println("Outer field: " + outerField); // access to non-static field
        }
    }

    static class StaticNested {
        void print() {
            // System.out.println(outerField); // Error, no access to non-static field
            System.out.println("Static nested class");
        }
    }
}

// Creating instances
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
Outer.StaticNested staticNested = new Outer.StaticNested();