Java lets you declare a class inside another class, or even inside a method. These nested classes keep helper code next to the only place it is used, and some of them can reach the private data of the class around them. There are four kinds: inner classes, static nested classes, local classes and anonymous classes. This lesson shows each one, explains when to choose it, and compares anonymous classes with lambdas.
In this lesson you will learn
- Inner (non-static) classes and the outer object
- Static nested classes
- Local classes declared inside a method
- Anonymous classes and how they compare with lambdas
- Capturing local variables
You should know classes and objects, interfaces and the static keyword.
Inner, Static Nested and Local Classes
import java.util.ArrayList;
import java.util.List;
class Playlist {
private final String title;
private final List<String> songs = new ArrayList<>();
Playlist(String title) { this.title = title; }
void add(String song) { songs.add(song); }
// Inner class: each Cursor belongs to one Playlist object
class Cursor {
private int pos = 0;
boolean hasNext() { return pos < songs.size(); } // reads the outer object's list
String next() { return title + " #" + (pos + 1) + ": " + songs.get(pos++); }
}
// Static nested class: a helper that needs no Playlist object
static class Stats {
static String summary(Playlist p) { return p.title + " has " + p.songs.size() + " songs"; }
}
}
public class Main {
public static void main(String[] args) {
Playlist road = new Playlist("Road Trip");
road.add("Song A");
road.add("Song B");
Playlist.Cursor c = road.new Cursor(); // inner object needs an outer object
while (c.hasNext()) System.out.println(c.next());
System.out.println(Playlist.Stats.summary(road));
// Local class: declared inside a method and used only there
class Shout {
String apply(String s) { return s.toUpperCase() + "!"; }
}
System.out.println(new Shout().apply("done"));
}
}
Output
Road Trip #1: Song A
Road Trip #2: Song B
Road Trip has 2 songs
DONE!
Cursoris an inner class: everyCursorobject is tied to onePlaylistobject and can read its private fieldssongsandtitledirectly.- Because of that link, you create it through an outer object:
road.new Cursor(). This is how many collections build their iterators. Statsis a static nested class. It has no link to an outer object, so it is created or used through the class name alone:Playlist.Stats.summary(road). It can still readPlaylist‘s private members when given an object.Shoutis a local class: declared insidemainand visible only there.- Prefer static nested classes unless the nested class truly needs the outer object. Each inner object keeps a hidden reference to its outer object, which uses memory and can keep it alive longer than expected.
Anonymous Classes
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Main {
interface Discount {
double apply(double price);
}
public static void main(String[] args) {
// Anonymous class: a one-off implementation with no name
Discount eid = new Discount() {
private final double rate = 0.20;
@Override
public double apply(double price) { return price * (1 - rate); }
};
System.out.println("Eid price: " + eid.apply(1500));
// The same thing as a lambda (works because Discount has one method)
Discount member = price -> price - 100;
System.out.println("Member price: " + member.apply(1500));
// Anonymous classes can capture effectively final local variables
int minLength = 5;
List<String> words = new ArrayList<>(List.of("tea", "biryani", "doi", "fuchka"));
words.removeIf(new java.util.function.Predicate<String>() {
@Override
public boolean test(String w) { return w.length() < minLength; }
});
words.sort(new Comparator<String>() {
@Override
public int compare(String a, String b) { return b.compareTo(a); }
});
System.out.println(words);
// The compiler gives each anonymous class a numbered name
System.out.println("Class name: " + eid.getClass().getName());
}
}
Output
Eid price: 1200.0
Member price: 1400.0
[fuchka, biryani]
Class name: Main$1
new Discount() { … }declares and creates an anonymous class in one expression: a class with no name that implementsDiscount. It is used once, right where it is written.- An anonymous class can have fields, such as
rate, and several methods. That is something a lambda cannot do. - When the interface has exactly one abstract method (a functional interface), a lambda is shorter:
price -> price - 100. - The anonymous
Predicateuses the local variableminLength. Anonymous classes and lambdas can only use local variables that are effectively final, meaning they are never reassigned. - The compiler gives each anonymous class a name made from the outer class plus a number, here
Main$1.
The Four Kinds of Nested Class
| Kind | Declared | Needs an outer object? | Typical use |
|---|---|---|---|
| Static nested | In a class, with static | No | Builders, helper types, nodes in a linked list |
| Inner | In a class, without static | Yes | Iterators and views over the outer object |
| Local | Inside a method | Yes, if the method is not static | A helper used only in that method |
| Anonymous | In an expression | Yes, if declared in instance code | One-off listeners, comparators, callbacks |
Common Mistakes
- Trying
new Inner()from a static method, which fails because there is no outer object. Useouter.new Inner()or make the class static. - Changing a local variable that an anonymous class or lambda uses, which causes “variable must be final or effectively final”.
- Writing long anonymous classes inside method calls. Give the class a name, or use a lambda.
- Confusing
this: inside an anonymous class,thisis the anonymous object. WriteOuter.thisto mean the outer object.
Practice Exercises
Exercise 1. Rewrite the anonymous Comparator from the second example as a lambda.
Show answer
words.sort((a, b) -> b.compareTo(a));
// or simply: words.sort(Comparator.reverseOrder());
Exercise 2. Add a static nested class Node with an int value and a Node next field to a LinkedNumbers class. Why should it be static?
Show answer
class LinkedNumbers {
private Node head;
private static class Node {
int value;
Node next;
Node(int value) { this.value = value; }
}
}
A node never needs to reach the list object it belongs to, so making it static avoids an unneeded hidden reference in every node.
Frequently Asked Questions
Is a lambda just an anonymous class?
No. A lambda can only implement a functional interface, has no fields of its own, and this inside it means the enclosing object. The JVM also creates lambdas differently, without a separate class file for each one.
Can a nested class be private?
Yes. Nested classes can use any access modifier. A private nested class is visible only inside its outer class, which is a good way to hide implementation details.
Summary
- Inner classes are tied to an outer object and can use its fields.
- Static nested classes need no outer object; prefer them by default.
- Local and anonymous classes live inside methods and expressions.
- For a single-method interface, a lambda is usually clearer than an anonymous class.
