Java ProgramsOOPStatic Nested Class

Static Nested Class in Java

intermediate·  OOP  ·  Nested Classes

Problem

A static nested class belongs to its outer class the way a static field would — it can be used without ever creating an instance of the outer class first.

Build a Book object step by step using a static nested Builder class, without needing an existing Book to start from.

Input
new Book.Builder().title("Effective Java").author("Joshua Bloch").year(2018).build()
Output
Effective Java by Joshua Bloch (2018)

Java Program

Java
class Book { String title; String author; int year; private Book(Builder builder) { this.title = builder.title; this.author = builder.author; this.year = builder.year; } @Override public String toString() { return title + " by " + author + " (" + year + ")"; } static class Builder { String title; String author; int year; Builder title(String title) { this.title = title; return this; } Builder author(String author) { this.author = author; return this; } Builder year(int year) { this.year = year; return this; } Book build() { return new Book(this); } // assembles the real Book from the collected fields } } public class StaticNestedClassDemo { public static void main(String[] args) { Book book = new Book.Builder() .title("Effective Java") .author("Joshua Bloch") .year(2018) .build(); System.out.println(book); } }

Output

Effective Java by Joshua Bloch (2018)

Core Logic

Collecting a Book's fields one at a time on a separate Builder object, then assembling the real Book only once every piece is set, avoids a constructor with a long, error-prone list of parameters.

How It Works
  1. 1static class Builder is nested inside Book, marked static so it doesn't need a Book instance to exist.
  2. 2Each setter method (title(), author(), year()) stores its value and returns this, which is what makes the calls chainable.
  3. 3build() passes the finished Builder into Book's private constructor, which copies the fields across.
  4. 4new Book.Builder() creates the nested class directly — there's no outer Book object anywhere yet at that point.
Chaining .title(...).author(...).year(...).build() assembles one Book from three separately-set values, printed as "Effective Java by Joshua Bloch (2018)".
💡

Key Point: Unlike a non-static inner class, Book.Builder never needs an outer Book instance to be constructed — that's exactly why the builder pattern works, since the whole point is building a Book that doesn't exist yet.

Key Concepts

static nested classbuilder patternmethod chaining

Related Programs