Nested classes: static nested, inner and anonymous
36 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Some classes are helpers of just one other class: a Builder for a Pizza, a Station for a metro line. Java lets you write them inside that class as nested classes, close to the only code that uses them.
Why put a class inside a class?
A nested class is a class declared inside another class. It is a member of the outer class, so it can use the outer class's private fields, methods and constructors. Java has four kinds: static nested, inner, local and anonymous.
A Builder that creates a Pizza is useless anywhere else. Putting it inside Pizza keeps the code together, lets it call Pizza's private constructor, and lets you make a helper private.
class Pizza { private String size;
private Pizza(Builder b) { // private: only code inside Pizza can call it size = b.size; }
static class Builder { // a nested class: Pizza.Builder private String size = "Medium";
Pizza build() { return new Pizza(this); } }}From outside, the nested class's full name is Outer.Nested, like Pizza.Builder. Which kind to write depends on one question: does the helper need an outer object?
Static nested class: no outer object needed
A static nested class is a nested class declared with static. Like a static method, it belongs to the outer class, not to an outer object, so it is created with new Outer.Nested() and cannot read the outer class's instance fields directly.
Pizza.Builder collects choices before any Pizza exists, so it cannot belong to a pizza object. Declare it static class Builder and create it with new Pizza.Builder().
Example 1 · A static nested Builder
final class Pizza { private final String size; private final boolean cheese; private final int toppings;
private Pizza(Builder b) { this.size = b.size; this.cheese = b.cheese; this.toppings = b.toppings; }
static class Builder { private String size = "Medium"; private boolean cheese; private int toppings;
Builder size(String size) { this.size = size; return this; }
Builder extraCheese() { cheese = true; return this; }
Builder addTopping() { toppings++; return this; }
Pizza build() { return new Pizza(this); } }
@Override public String toString() { return size + " pizza, cheese: " + cheese + ", toppings: " + toppings; }}
public class BuilderDemo { public static void main(String[] args) { Pizza p = new Pizza.Builder().size("Large").extraCheese().addTopping().addTopping().build(); Pizza plain = new Pizza.Builder().build(); System.out.println(p); System.out.println(plain); }}Large pizza, cheese: true, toppings: 2 Medium pizza, cheese: false, toppings: 0
What this code does
new Pizza.Builder()needs noPizzaobject, becauseBuilderis static. It collects the choices step by step, thenbuild()makes one immutablePizza.Pizza's constructor isprivate, yetBuildercan call it: a nested class can use the outer class's private members.
Example 2 · A private static nested Node
class MetroLine { private static class Station { String name; Station next;
Station(String name) { this.name = name; } }
private Station first; private Station last;
void add(String name) { Station s = new Station(name); if (first == null) { first = s; } else { last.next = s; } last = s; }
void print() { for (Station s = first; s != null; s = s.next) { System.out.print(s.name + (s.next != null ? " -> " : "\n")); } }}
public class MetroDemo { public static void main(String[] args) { MetroLine purple = new MetroLine(); purple.add("Majestic"); purple.add("MG Road"); purple.add("Indiranagar"); purple.print(); }}Majestic -> MG Road -> Indiranagar
What this code does
- Each
Stationobject (a node) holds a name and a reference to the next station, forming a chain. Stationisprivate, so onlyMetroLinecan use it; outside code just callsaddandprint.
Reading an instance field directly, like plain size inside Builder, gives non-static variable size cannot be referenced from a static context. Through an object reference, like p.size, it may still read private fields. When in doubt, make a nested class static.
Inner class: tied to one outer object
An inner class is a nested class declared without static. Each inner object is created for one outer object and keeps a hidden link to it, so its methods can read that object's fields directly, even private ones.
A Classroom.Student should print its own classroom's section. As an inner class, each Student object remembers the Classroom object it was made for.
Example 3 · An inner class reads the outer object's fields
class Classroom { private String section; private int count;
Classroom(String section) { this.section = section; }
class Student { private String name;
Student(String name) { this.name = name; count++; }
void introduce() { System.out.println(name + " of class " + section + " (student " + count + ")"); } }
Student admit(String name) { return new Student(name); }}
public class InnerDemo { public static void main(String[] args) { Classroom room = new Classroom("12-B"); Classroom.Student a = room.admit("Kavya"); Classroom.Student b = room.new Student("Rohan"); a.introduce(); b.introduce(); }}Kavya of class 12-B (student 2) Rohan of class 12-B (student 2)
What this code does
- Each
Studentbelongs to oneClassroomobject, so it can read and change the privatesectionandcountof that classroom. - Inside
Classroomyou writenew Student(...); from outside you need an outer object:room.new Student("Rohan").
From outside you need the outer object first: room.new Student("Rohan"). If an inner field and an outer field share a name, Classroom.this.section reaches the outer one.
Fix the error
Static nested or inner?
Read the error, then pick the line that fixes it.
Round 1 of 2
Printer must print the title of its own Report object.
Error
error: non-static variable title cannot be referenced from a static context
Anonymous classes
An anonymous class is a class with no name that is defined and used to create one object in a single new expression, as in new Discount() { ... }. It implements an interface or extends a class just once, where it is needed.
You wrote one in Functional interfaces and lambdas (opens in a new tab). An anonymous class can also extend a class and keep fields of its own, which a lambda cannot.
Example 4 · An anonymous class with a field of its own
class Notification { void send(String msg) { System.out.println("Notice board: " + msg); }}
public class AnonymousDemo { public static void main(String[] args) { Notification urgent = new Notification() { private int sent = 0;
@Override void send(String msg) { sent++; System.out.println("URGENT " + sent + ": " + msg.toUpperCase()); } };
urgent.send("Exam hall changed"); urgent.send("Bus at 7 am"); new Notification().send("Library closed on Sunday"); System.out.println(urgent.getClass().getSimpleName().isEmpty()); }}URGENT 1: EXAM HALL CHANGED URGENT 2: BUS AT 7 AM Notice board: Library closed on Sunday true
What this code does
new Notification() { ... }defines a nameless child of the classNotification, overridessend, and creates one object of it.- The field
sentlives in that one object and counts between calls. The class really has no simple name, sogetSimpleName()is empty.
Example 5 · Mistake: changing a variable used by an anonymous class
interface Greeter { void greet();}
public class CaptureDemo { public static void main(String[] args) { String name = "Diya"; Greeter g = new Greeter() { @Override public void greet() { System.out.println("Hello, " + name); } }; name = "Arjun"; g.greet(); }}CaptureDemo.java:11: error: local variables referenced from an inner class must be final or effectively final
System.out.println("Hello, " + name);
^
1 errorWhat this code does
- An anonymous (or local) class keeps its own copy of the local variables it uses. To keep that copy correct, Java requires that the variable never changes.
- Remove
name = "Arjun";(or use a new variable) and it compiles. Lambdas follow the same rule.
Anonymous classes and lambdas share one rule for the method's local variables they use: those variables must be effectively final, never changed after they are set. The next example breaks that rule.
Local classes, and which kind to use
A local class is a named class declared inside a method. It can be used only inside that method, and, like an anonymous class, it can use the method's local variables only if they are effectively final.
A report method needs a small Row helper that no other code uses. Declared inside the method, it has a name, so the method can create many objects of it.
Example 6 · A local class inside a method
public class ReportCard { static void print(String[] names, int[] marks) { class Row { String name; int mark;
Row(String name, int mark) { this.name = name; this.mark = mark; }
String grade() { return mark >= 60 ? "First class" : "Second class"; } }
for (int i = 0; i < names.length; i++) { Row r = new Row(names[i], marks[i]); System.out.println(r.name + ": " + r.mark + ", " + r.grade()); } }
public static void main(String[] args) { String[] names = { "Aarav", "Diya", "Rohan" }; int[] marks = { 72, 58, 64 }; print(names, marks); }}Aarav: 72, First class Diya: 58, Second class Rohan: 64, First class
What this code does
Rowis declared insideprint, so onlyprintcan use it;maincannot even see the nameRow.- Unlike an anonymous class it has a name and a constructor, so the loop creates a new
Rowfor every student.
Local classes are rare. To choose a kind, ask what the helper needs:
- no outer object → static nested (the default)
- the outer object's fields → inner
- used inside one method only → local, or anonymous for a single object
- one method of a functional interface → a lambda
static when the outer object is not needed.Next step
Check your understanding
12 quick questions