Java ProgramsOOPNested Class

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. 1static class Nested is defined inside Outer, marked static.
  2. 2Because it's static, Nested doesn't need — and can't use — any particular Outer instance to exist.
  3. 3new Outer.Nested() creates it directly, using Outer's name purely as a namespace, the same way you'd write Outer.SOME_CONSTANT.
  4. 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

Related Programs