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
class Inner(nostatic) is defined insideOuter, which is what makes it a true inner class rather than a static nested one. - 2Creating one requires an existing
Outerobject first:Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();— theouter.newsyntax binds the newInnerto that specific instance. - 3Inside
Inner,messagerefers directly toOuter's private field, with no getter and no reference passed intoInner's constructor — the compiler wires that connection up automatically. - 4A static nested class couldn't do this — without an implicit outer reference, it would have no instance of
Outerto readmessagefrom 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