Java ProgramsOOPInner Class

Inner Class in Java

intermediate·  OOP  ·  Nested Classes

Problem

A non-static inner class is tied to a specific instance of its enclosing class — it can't exist without one, but in exchange it gets direct access to that instance's fields, even private ones, without them ever being passed in.

Create a non-static inner class that reads a private field from its enclosing Outer instance.

Input
outer.new Inner()
Output
Outer message: Hello from Outer

Java Program

Java
public class Outer { private String message = "Hello from Outer"; class Inner { void show() { System.out.println("Outer message: " + message); // reads Outer's private field directly } } public static void main(String[] args) { Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); // requires an existing Outer instance inner.show(); } }

Output

Outer message: Hello from Outer

Core Logic

Leaving the inner class non-static ties every instance of it to one specific Outer object, which is exactly what lets it reach into that object's private fields directly.

How It Works
  1. 1class Inner (no static) is defined inside Outer, which is what makes it a true inner class rather than a static nested one.
  2. 2Creating one requires an existing Outer object first: Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); — the outer.new syntax binds the new Inner to that specific instance.
  3. 3Inside Inner, message refers directly to Outer's private field, with no getter and no reference passed into Inner's constructor — the compiler wires that connection up automatically.
  4. 4A static nested class couldn't do this — without an implicit outer reference, it would have no instance of Outer to read message from at all.
Calling inner.show() prints "Outer message: Hello from Outer", reading message straight from the specific Outer instance inner was created through.
💡

Key Point: Every non-static inner class instance secretly holds a reference back to the outer instance that created it — that's what makes direct field access possible, and it's also exactly why creating one always requires an existing outer object first.

Key Concepts

inner classouter.new Inner() syntaximplicit outer reference

Related Programs