All 15 Inner Classes & Anonymous Classes questions
More in Inner Classes & Anonymous Classes
Advertisement
Java › Inner Classes & Anonymous Classes

What is a non-static (inner) class in Java, and how does its relationship to an enclosing instance differ from a regular top-level class?

Beginner

Answer

A non-static inner class is defined within another class and holds an implicit reference to a specific instance of its enclosing class, meaning an inner class instance cannot exist independently of an associated outer instance and can freely access that outer instance's fields and methods (including private ones) without any special qualification -- this differs fundamentally from a regular top-level class, which has no inherent connection to any other class's instances, requiring inner class instances to always be created through (or in relation to) an existing outer instance.
public class Outer {
    private int value = 42;

    class Inner {
        void printValue() {
            System.out.println(value);  // accesses Outer's private field directly, no qualification needed
        }
    }
}

Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();  // requires an outer instance to create
inner.printValue();  // prints 42
Real-world example A GUI event-handling inner class defined within a Window class directly accesses the Window's private fields (like its title or state) to update the UI in response to user interaction, without needing to pass those fields explicitly since the inner class automatically retains a reference to its specific enclosing Window instance.

Common follow-ups: Why does creating an inner class instance require the unusual outer.new Inner() syntax rather than just new Inner()?;What happens to memory if the outer instance is kept alive solely because an inner class instance derived from it is still referenced?