Command Palette

Search for a command to run...

Back to the lesson: Topic 5.13 — Nested, Inner, Local and Anonymous Classes
Core Java · Example 1 of 5

Static nested vs inner: who needs an outer object?

Java lets you declare a class inside another class, or even inside a method. A static nested class is an ordinary class that lives in another's namespace; an inner class is tied to one outer object through a hidden reference; local and anonymous classes live inside a block and can read effectively final local variables. Since Java 8, a lambda replaces most anonymous classes that implement a one-method interface.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write an IntList singly linked list whose Node is a private static nested class. Add add(int) and a toString() that prints [3, 1, 4].

02

Write Range implements Iterable<Integer> whose iterator is a private inner class reading the outer from and to fields. Loop over new Range(2, 6) with an enhanced for.

03

Using an anonymous class, create a Supplier<Integer> ticket machine that returns 1, 2, 3 on successive calls. Explain why a plain lambda can't hold that counter itself.

04

Build three Runnables in a for (int i ...) loop that print task 0, task 1, task 2, plus two more from an enhanced for over List.of("x", "y").

Explain it without notes

01

What are the four kinds of nested classes, and how do they differ?

02

Why can an inner class cause a memory leak, and how do you avoid it?

03

Why must captured local variables be final or effectively final?

04

How does javac compile nested classes and lambdas? Name the files and synthetic members.

05

When would you still choose an anonymous class over a lambda?

Static nested vs inner: who needs an outer object?
Sign in to run this example in your browser.

Expected output

Road trip: Song A
Road trip: Song B
owner is road? true
2 songs