Java Nested Classes: Inner Classes and Static Nested Classes (OCP 21)
Member-level nested classes for the OCP 21 exam: the four kinds of nested class, inner classes and the outer.new Inner() syntax, Outer.this for shadowed members, static nested classes, nested records, enums and interfaces that are implicitly static, modifiers and generated class files.
kvi5hnuCode Sprout team member6 min readOn this page
A nested class is a class declared inside another type. Java has four kinds, and this article covers the two declared at member level, next to fields and methods. The next article covers the two declared inside method bodies.
| Kind | Declared | Needs an outer instance? |
|---|---|---|
| inner class (member inner class) | at member level, without static | yes |
| static nested class | at member level, with static | no |
| local class | inside a method or block | (depends on context) |
| anonymous class | inline in a new expression | (depends on context) |
"Nested class" is the umbrella term for all of them, and it also covers nested interfaces, enums, records and annotations. Nested classes are useful for helpers that only make sense inside another class: they keep the helper hidden and the code organized. The exam likes edge cases, though, and some exam code is deliberately harder to read than anything you'd write in practice.
Inner classes
An inner class is a non-static member class. Every inner object is created for one specific outer object, and it keeps a hidden reference to that object. As a result, an inner class:
- can read and write all members of the outer object, including
privateones, with no prefix - can use any access modifier (
public,protected, package orprivate), unlike a top-level class - can be
abstractorfinal, extend a class and implement interfaces - can declare
staticmembers (allowed since Java 16)
public class Library {
private final String name = "City";
class Loan {
private final String title;
Loan(String title) { this.title = title; }
String describe() { return title + " from " + name; } // outer private field
}
void lendDemo() {
Loan l = new Loan("Dune"); // inside an instance method: this.new Loan(...)
System.out.println(l.describe()); // Dune from City
}
}
The access works both ways. The outer class can read an inner object's private members too, as in new Loan("x").title.
Creating an inner object
Inside an instance method of the outer class, new Loan(...) implicitly uses this as the outer object. Anywhere else, you need an outer object and the special syntax outerRef.new Inner(...):
Library city = new Library();
Library.Loan a = city.new Loan("Emma"); // explicit outer instance
Library.Loan b = new Library().new Loan("Ivy"); // legal, but hard to read
Common errors:
public class Library {
class Loan { }
static void audit() {
new Loan(); // DOES NOT COMPILE: non-static variable this cannot be referenced from a static context
}
}
class Kiosk {
void m() {
new Library.Loan(); // DOES NOT COMPILE: an enclosing instance that contains Library.Loan is required
}
}
Access modifiers still apply. If Loan were private, no code outside Library could name it at all ("Library.Loan has private access in Library").

Shadowed names and Outer.this
If an inner class declares a member with the same name as an outer member, the inner one wins. To reach the outer one, write OuterName.this.member:
public class Tower {
private int x = 10;
class Floor {
private int x = 20;
class Room {
private int x = 30;
void showX(int x) {
System.out.println(x); // parameter
System.out.println(this.x); // 30: Room's field
System.out.println(Floor.this.x); // 20
System.out.println(Tower.this.x); // 10
}
}
}
}
Tower t = new Tower();
Tower.Floor f = t.new Floor();
Tower.Floor.Room r = f.new Room(); // the type is spelled Tower.Floor.Room outside Tower
r.showX(40); // 40, 30, 20, 10
Each level of nesting needs its own outer object, so the objects are created from the outside in.
Static nested classes
A static nested class is declared with static. It has no outer instance, so it works like a top-level class that lives in the outer class's namespace:
public class Park {
private static int ridesOpened;
private int visitors;
static class Ride {
private int price = 6;
void open() { ridesOpened++; } // OK: static outer member
int crowd() { return visitors; } // DOES NOT COMPILE: no Park object here
}
public static void main(String[] args) {
var r = new Ride(); // no Park instance needed
System.out.println(r.price); // outer class can read the nested class's private field
}
}
Park.Ride r2 = new Park.Ride(); // from outside: qualified name, no outer object
Compared with a top-level class, a static nested class:
- must be referred to through the outer name (
Park.Ride), or imported (import com.zoo.Park.Ride;) - can be
privateorprotected - shares private access with its outer class, in both directions
- can't read the outer class's instance members, and can't use
Park.this
The JDK uses them widely. Map.Entry is a nested interface, and builder classes are usually static nested classes.
Nested records, enums and interfaces are always static
A nested record, enum or interface is implicitly static, whether or not you write static. So it can be created without an outer object, but it can't touch outer instance members:
class Band {
String name = "Echo";
static Tour make() { return new Tour("spring"); } // OK: Tour is static
record Tour(String season) {
void play() { System.out.print(name); } // DOES NOT COMPILE: name is an instance field
}
}
If you replaced the record with an ordinary inner class Tour, the result would flip: play() would compile, and make() wouldn't, because a static method has no Band object to attach a new inner object to.
A class declared inside an interface is also implicitly public static.
Modifiers and class files
| Inner class | Static nested class | |
|---|---|---|
| Access modifiers | all four | all four |
abstract / final | allowed | allowed |
| Instance and static members | yes (static since Java 16) | yes |
| Extends a class / implements interfaces | yes | yes |
| Accesses outer instance members | yes | no |
| Created with | outer.new Inner() | new Outer.Nested() |
Compiling Library.java produces Library.class plus Library$Loan.class for the nested class, and A$B$C.class for deeper nesting. One source file can create many class files.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- Inner classes may declare
staticmembers since Java 16. Older books still say they can't.
Exam traps from this article
A complete example
A Library has an inner Loan class that registers itself in its library's list, a static nested Stats class, and a nested Hours record. Two libraries show that every loan belongs to its own outer object.
import java.util.ArrayList;
import java.util.List;
public class Solution {
static class Library {
private final String name;
private final List<Loan> loans = new ArrayList<>();
private static int librariesOpened;
Library(String name) { this.name = name; librariesOpened++; }
// Inner class: every Loan belongs to one Library object
class Loan {
private final String title;
private final int days;
Loan(String title, int days) {
this.title = title;
this.days = days;
loans.add(this); // outer instance field, no prefix needed
}
String describe() {
String name = "shadow"; // local hides the outer field
return title + " (" + days + " days) from " + Library.this.name
+ " [local name=" + name + "]";
}
}
// Static nested class: no Library instance needed or available
static class Stats {
static String summary() {
return "libraries opened: " + librariesOpened; // static outer member: OK
}
}
// Nested record: implicitly static
record Hours(int open, int close) {
int length() { return close - open; }
}
Loan lend(String title) { return new Loan(title, 14); } // implicit this.new Loan
int totalDays() {
int sum = 0;
for (Loan l : loans) sum += l.days; // outer reads inner's private field
return sum;
}
}
public static void main(String[] args) {
Library city = new Library("City");
Library campus = new Library("Campus");
Library.Loan a = city.lend("Dune");
Library.Loan b = city.new Loan("Emma", 7); // explicit outer instance
Library.Loan c = campus.new Loan("Ulysses", 21);
System.out.println(a.describe());
System.out.println(b.describe());
System.out.println(c.describe());
System.out.println("City loan days: " + city.totalDays()
+ ", Campus loan days: " + campus.totalDays());
System.out.println(Library.Stats.summary());
Library.Hours h = new Library.Hours(9, 17); // no Library object needed
System.out.println(h + " is " + h.length() + " hours");
}
}
Output:
Dune (14 days) from City [local name=shadow]
Emma (7 days) from City [local name=shadow]
Ulysses (21 days) from Campus [local name=shadow]
City loan days: 21, Campus loan days: 21
libraries opened: 2
Hours[open=9, close=17] is 8 hours
Points to notice:
city.lend("Dune")creates the loan with an implicitthis, whilecity.new Loan(...)andcampus.new Loan(...)name the outer object explicitly.- Each
Loanadds itself toloansof its library, so the totals are counted separately. - Inside
describe, a local variable callednamehides the outer field, andLibrary.this.namestill reaches it. Library.Stats.summary()andnew Library.Hours(9, 17)work with noLibraryobject at all.
Common questions
When should a nested class be static? Almost always, unless it truly needs the outer object's state. An inner object keeps its outer object reachable, which can keep large objects alive longer than intended.
Can a static nested class have instance fields? Yes. "Static" describes its relation to the outer class, not its own members.
Do nested classes need to be in their own file?
No. They're declared inside the outer class's file, and the compiler produces a separate .class file for each one.
Summary
- Inner classes are non-static member classes. Each instance is bound to an outer object, and it can use all outer members, including private ones.
- Create inner objects with
outerRef.new Inner(), or with plainnew Inner()inside outer instance methods. UseOuter.this.xto reach a shadowed outer member. - Static nested classes need no outer object, and they can only use the outer class's static members.
- Nested records, enums and interfaces are implicitly static. Classes inside interfaces are
public static. - Member nested classes can use any access modifier and
abstractorfinal. The compiler generatesOuter$Nested.classfiles.
Practice quiz
Test yourself with the nested classes quiz: 10 exam-style questions with explanations.
Previous: Java Record Patterns: Deconstruction, Nesting and switch (OCP 21)
Related reading
- Java Sealed Classes and Interfaces: sealed, permits, final and non-sealed (OCP 21)
- Java Interfaces: Declaring, Implementing and Inheriting Abstract Methods (OCP 21)
- Java Abstract Classes and Abstract Methods (OCP 21)
- Java Inheritance and Class Modifiers: extends, Object, this and super (OCP 21)
- Java while, do/while, for and for-each Loops (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.