Nested Class in Java
beginner· OOP · Nested Classes
Problem
A nested class is any class defined inside another class — Java splits these into two kinds, static nested classes and non-static inner classes, and a static nested class is the simpler of the two since it behaves like a regular top-level class that just happens to live inside another one's namespace.
Create a static nested class inside an Outer class and instantiate it directly.
Input
new Outer.Nested()
Output
Inside the nested class
Java Program
Java
public class Outer {
static class Nested {
void display() {
System.out.println("Inside the nested class");
}
}
public static void main(String[] args) {
Outer.Nested nested = new Outer.Nested(); // no Outer instance needed
nested.display();
}
}Output
Inside the nested class
Core Logic
Marking the inner class static means it behaves independently of any Outer instance, so it can be created directly through Outer's namespace.
How It Works
- 1
static class Nestedis defined insideOuter, markedstatic. - 2Because it's static,
Nesteddoesn't need — and can't use — any particularOuterinstance to exist. - 3
new Outer.Nested()creates it directly, usingOuter's name purely as a namespace, the same way you'd writeOuter.SOME_CONSTANT. - 4This is the simplest of the two nested class categories — the non-static "inner class" variant works differently and needs its own dedicated example.
Calling
new Outer.Nested().display() prints "Inside the nested class", with no Outer object ever created.💡
Key Point: "Nested class" is the umbrella term for anything declared inside another class — this static version is the more self-contained of the two kinds, since it carries no hidden connection back to an enclosing instance.
Key Concepts
static nested classOuter.Nested syntaxnested class basics