SyntaxPilot
Courses/Java/Lesson 23

Java · Lesson 23 of 51 · 11 min

Inner, nested and anonymous classes

queued

These are the notes for Java episode 23. Episode 22 ended with a new itch: a Chapter class only makes sense as part of a Book, yet it sits in the open as a top-level class anyone can use, and it can't even read the book's private title. Today you fix that by putting classes inside classes. You'll invent the inner class (tied to one outer object, sees its private fields), the static nested class (belongs to the outer class, needs no outer object), and the anonymous class (a class with no name, written and used exactly once), plus the rule about effectively final variables. Every example was run with javac 21.

The problem: a chapter without a book

A library program has Book objects, and every book has chapters. The obvious way is to write Chapter as a separate, top-level class that stores a reference to its book:

class Book {
    private String title;
    Book(String title) {
        this.title = title;
    }
}

class Chapter {
    Book book;
    String name;
    Chapter(Book book, String name) {
        this.book = book;
        this.name = name;
    }
    void print() {
        System.out.println(book.title + " > " + name);
    }
}

public class Main {
    public static void main(String[] args) {
        Book b = new Book("Java Basics");
        new Chapter(b, "Loops").print();
        new Chapter(null, "Ghost chapter").print();
    }
}
Main.java:16: error: title has private access in Book
        System.out.println(book.title + " > " + name);
                               ^
1 error

Two problems:

  1. Chapter is an outsider, so it can't see Book's private title (we made it private for encapsulation in episode 17). Making title public would let everyone read and change it.
  2. Anyone can create a "ghost chapter" that belongs to no book (new Chapter(null, ...)), which would crash with a NullPointerException the moment it tried to print.

Why it fails: Chapter lives outside the walls of Book, even though it is part of a book.

Real-life example: a hotel has three kinds of "inside" things

In a hotel In Java Key idea
Room 204's minibar: part of one room, exists because the room exists Inner class tied to one outer object
The hotel's room-service menu card: the hotel's, but no room needed Static nested class tied to the outer class
A cab booked for one guest's single ride: no name in the staff list Anonymous class defined where it's used, used once

All three are nested classes: classes declared inside another class. The outer one is called the enclosing (or outer) class.

Inner classes

An inner class is a class declared inside another class without the word static. Move Chapter inside Book:

class Book {
    private String title;
    Book(String title) {
        this.title = title;
    }

    class Chapter {
        String name;
        Chapter(String name) {
            this.name = name;
        }
        void print() {
            System.out.println(title + " > " + name);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Book java = new Book("Java Basics");
        Book c = new Book("C in Depth");
        Book.Chapter ch1 = java.new Chapter("Loops");
        Book.Chapter ch2 = c.new Chapter("Pointers");
        ch1.print();
        ch2.print();
    }
}
Java Basics > Loops
C in Depth > Pointers

What changed:

  • Chapter no longer has a book field, yet print() uses title directly, even though it's private. Private means "private to the class", and an inner class is part of the class.
  • Every Chapter object carries a hidden reference to the Book object that created it. That's how title means "my book's title": ch1 printed Java Basics, ch2 printed C in Depth.
  • Outside Book, the type is written Book.Chapter: the inner class's full name goes through its outer class.
  • To create one from outside, you need an outer object first: java.new Chapter("Loops"). Inside Book's own (non-static) methods you can simply write new Chapter("Loops"), because this is the book.

The trap: an inner object needs an outer object

Book.Chapter ch = new Book.Chapter("Loops");
Main.java:20: error: an enclosing instance that contains Book.Chapter is required
        Book.Chapter ch = new Book.Chapter("Loops");
                          ^
1 error

"Enclosing instance" means the outer object. Which book is this chapter part of? The ghost-chapter bug is now a compile error. No room, no minibar.

If the inner class is inside the class that holds main and you write new Chapter() inside the static main, you get a related message:

Main.java:9: error: non-static variable this cannot be referenced from a static context
        Chapter ch = new Chapter();
                     ^
1 error

main is static, so there is no this (no outer object) to link the chapter to.

Outer.this: reaching the outer object

If the inner class has a field with the same name as an outer field, the plain name means the inner one. Book.this is the hidden link to the outer object:

class Book {
    private String title;
    class Chapter {
        String title;          // same name!
        void print() {
            System.out.println(Book.this.title + " > " + title);
        }
    }
}

What javac produces

Compiling creates a separate class file for each nested class, named Outer$Inner.class:

Book.class  Book$Chapter.class  Main.class

To the JVM it's an ordinary class; the compiler adds the link to the outer object for you.

Static nested classes

The problem: one method, two answers

The library's search method must answer two things: was it found? (a boolean) and on which shelf? (an int). But a method returns only one value. So we bundle both into a tiny class, Result. It only makes sense for the library's search, but it doesn't need any particular library object, just like the menu card doesn't need a room. That's a static nested class:

class Library {
    private static String[] titles = { "Java Basics", "C in Depth", "Let Us Python" };

    static class Result {
        boolean found;
        int shelf;
        Result(boolean found, int shelf) {
            this.found = found;
            this.shelf = shelf;
        }
    }

    static Result search(String title) {
        for (int i = 0; i < titles.length; i++) {
            if (titles[i].equals(title)) return new Result(true, i + 1);
        }
        return new Result(false, -1);
    }
}

public class Main {
    public static void main(String[] args) {
        Library.Result r = Library.search("C in Depth");
        System.out.println(r.found + ", shelf " + r.shelf);
        Library.Result x = Library.search("Harry Potter");
        System.out.println(x.found + ", shelf " + x.shelf);
    }
}
true, shelf 2
false, shelf -1
  • new Result(...) works with no outer object, and from outside you write new Library.Result(true, 2).
  • A static nested class has no hidden link, so it can use only the outer class's static members (it can read private static ones, like titles). Using an instance field fails:
Main.java:4: error: non-static variable name cannot be referenced from a static context
        void show() { System.out.println(name); }
                                         ^
1 error

Real Java uses this pattern all the time: Map.Entry is a nested type of Map, and many classes have a nested Builder.

Inner vs static nested

Inner class Static nested class
Declared as class Chapter { } inside Book static class Result { } inside Library
Linked to an outer object? Yes, a hidden reference No
Can use outer instance fields? Yes, even private No, only static members
Created with book.new Chapter("Loops") new Library.Result(true, 2)
Real-life picture the room's minibar the hotel's menu card
When to use the helper needs its outer object's data the helper just belongs with the class

Rule of thumb: if the helper doesn't need the outer object, make it static. It's simpler and doesn't keep the outer object alive in memory.

Anonymous classes

The problem: a rule needed exactly once

The library shop has a Discount interface (like the interfaces in episode 21). For Diwali week, books are 10% off. The normal way is a whole named class, class DiwaliDiscount implements Discount { ... }, created once and never used again. Then Holi, Eid, Christmas: another tiny named class each time. An anonymous class writes the class right where it's used, without a name:

interface Discount {
    double apply(double price);
}

public class Main {
    public static void main(String[] args) {
        Discount diwali = new Discount() {
            @Override
            public double apply(double price) {
                return price * 0.9;
            }
        };
        System.out.println(diwali.apply(1000));
        System.out.println(diwali.getClass().getName());
    }
}
900.0
Main$1
  • new Discount() { ... } does not create an object of the interface (that's impossible). It declares a brand-new class with no name that implements Discount, and creates its only object, in one expression.
  • The compiler names it for you: Main$1, the first anonymous class in Main (and writes Main$1.class).
  • It can also extend a class: new Thread() { ... } (episode 39).
  • The whole thing is one statement, so it ends with };. Forget the semicolon:
Main.java:11: error: ';' expected
        }
         ^
1 error
  • It can't have a constructor (it has no name to give one), and it is used in exactly one place.

The trap: effectively final

int used = 0;
Discount diwali = new Discount() {
    @Override
    public double apply(double price) {
        used++;
        return price * 0.9;
    }
};
Main.java:11: error: local variables referenced from an inner class must be final or effectively final
                used++;
                ^
1 error

The anonymous object can live longer than main's local variables, so Java gives it a copy of their values. If either side could change the variable, the copy and the original would disagree. So you may read a local variable inside an anonymous (or local) class, but it must never change after it's set. A variable that is never reassigned is called effectively final, even if you didn't write final.

Need a counter? Make it a field of the anonymous class itself:

Discount diwali = new Discount() {
    int used = 0;
    @Override
    public double apply(double price) {
        used++;
        System.out.println("used " + used + " time(s)");
        return price * 0.9;
    }
};
diwali.apply(1000);
diwali.apply(500);
used 1 time(s)
used 2 time(s)

Bonus: local classes

A named class can also be declared inside a method. It's visible only in that method (a local class), and follows the same effectively-final rule:

public class Main {
    public static void main(String[] args) {
        class Counter {
            int n;
            void tick() { n++; }
        }
        Counter c = new Counter();
        c.tick(); c.tick();
        System.out.println("Ticks: " + c.n);
    }
}
Ticks: 2

javac names it Main$1Counter.class.

What you just invented

Problem Fix
A helper class that belongs to one object and needs its private data inner class
A helper that belongs with a class but needs no object static nested class
A class needed exactly once anonymous class
An anonymous class must not change outside locals effectively final rule

In episode 36, lambdas shrink an anonymous class with one method into a single line: Discount diwali = price -> price * 0.9;.

The next problem: each book has a status: available, issued or lost, stored as a String. Someone types "AVIALABLE"; it compiles perfectly and the book disappears from every search. We need a type that allows only a fixed list of values. Episode 24: enums and records.

Common mistakes (and the real error messages)

Mistake Real message Why Fix
Outside class reads a private field error: title has private access in Book private = only inside the class make it an inner class (or add a getter)
new Book.Chapter("Loops") error: an enclosing instance that contains Book.Chapter is required an inner object needs an outer object book.new Chapter("Loops")
new Chapter() inside static main of the outer class error: non-static variable this cannot be referenced from a static context static main has no this create an outer object first, or make the nested class static
Static nested class uses an instance field error: non-static variable name cannot be referenced from a static context no link to an outer object make the field static, or use an inner class
Changing a local inside an anonymous class error: local variables referenced from an inner class must be final or effectively final it holds a copy use a field of the anonymous class
No ; after the anonymous class body error: ';' expected it's one statement end with };

Mini project: a train with coaches, tickets and a student discount

interface Discount {
    double apply(double fare);
}

class Train {
    private final int number;
    private final String name;
    Train(int number, String name) {
        this.number = number;
        this.name = name;
    }

    class Coach {
        private final String code;
        Coach(String code) { this.code = code; }
        void show() {
            System.out.println("Coach " + code + " of " + number + " " + name);
        }
    }

    static class Ticket {
        final String from, to;
        final double fare;
        Ticket(String from, String to, double fare) {
            this.from = from; this.to = to; this.fare = fare;
        }
        Ticket with(Discount d) {
            return new Ticket(from, to, d.apply(fare));
        }
        @Override public String toString() {
            return from + " -> " + to + " : Rs " + fare;
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Train t = new Train(12951, "Rajdhani");
        Train.Coach s3 = t.new Coach("S3");
        Train.Coach b1 = t.new Coach("B1");
        s3.show();
        b1.show();

        Train.Ticket ticket = new Train.Ticket("Mumbai", "Delhi", 2500);
        Discount student = new Discount() {
            @Override
            public double apply(double fare) {
                return fare * 0.8;
            }
        };
        System.out.println(ticket);
        System.out.println(ticket.with(student));
    }
}
Coach S3 of 12951 Rajdhani
Coach B1 of 12951 Rajdhani
Mumbai -> Delhi : Rs 2500.0
Mumbai -> Delhi : Rs 2000.0

Class files produced: Train.class, Train$Coach.class, Train$Ticket.class, Main$1.class, Discount.class, Main.class.

Practice

  1. Inside Train, add a method Coach addCoach(String code) that creates and returns a coach. Why don't you need this.new there?
  2. Can a static nested class have its own instance fields and multiple objects? Try it with Train.Ticket.
  3. Rewrite the anonymous student discount as a named class StudentDiscount. How many lines did the anonymous version save?
Solutions

1. Coach addCoach(String code) { return new Coach(code); }. Inside an instance method of Train, this is the train, so new Coach(code) is automatically linked to it (it means this.new Coach(code)).

2. Yes. "Static" only means it has no link to an outer object; it is a normal class otherwise. new Train.Ticket("Pune", "Goa", 900) and new Train.Ticket("Delhi", "Agra", 400) are two independent objects with their own fields.

3.

class StudentDiscount implements Discount {
    @Override
    public double apply(double fare) {
        return fare * 0.8;
    }
}
// in main:
Discount student = new StudentDiscount();

A named top-level class, used once. The anonymous version keeps the rule where it's used and adds no new name to the program.

Quick quiz

class Room {
    int number;
    Room(int n) { number = n; }
    class Minibar {
        void show() { System.out.println("Minibar of " + number); }
    }
}
// in main:
Room r = new Room(204);

Which line creates the inner object correctly?

A) Room.Minibar m = new Room.Minibar(); B) Room.Minibar m = r.new Minibar(); C) Minibar m = new Minibar(r); D) Room.Minibar m = Room.new Minibar();

Answer

B. Minibar is an inner class, so it needs a Room object: r.new Minibar(). Calling m.show() prints:

Minibar of 204

Option A fails with error: an enclosing instance that contains Room.Minibar is required.

Interview questions

  1. What are the kinds of nested classes in Java? Static nested classes and inner classes; inner classes include local classes (declared in a method) and anonymous classes.
  2. Inner class vs static nested class? An inner class holds a reference to an outer object and can use its instance members; a static nested class has no such reference and can use only static members of the outer class.
  3. How do you create an inner class object from outside? Outer.Inner x = outerObject.new Inner();
  4. How does an inner class refer to the outer object? Outer.this.
  5. What is an anonymous class? A class without a name, declared and instantiated in one expression, that extends a class or implements an interface; used once.
  6. Can an anonymous class have a constructor? No, it has no name. It can use an instance initialiser block, and pass arguments to its superclass constructor.
  7. What does "effectively final" mean? A local variable that is never reassigned after initialisation; only such variables can be used inside local/anonymous classes and lambdas.
  8. Why can inner classes cause memory leaks? Each inner object keeps its outer object reachable; if the inner object lives long (e.g. a listener), the outer object can't be garbage collected. Prefer static nested classes when the link isn't needed.
  9. What are the class file names of nested classes? Outer$Inner.class, Outer$1.class for anonymous classes, Outer$1Local.class for local classes.

Glossary

Term Meaning Example
Nested class Any class declared inside another class Book.Chapter, Library.Result
Outer (enclosing) class The class that contains a nested class Book
Inner class A non-static nested class, linked to one outer object class Chapter inside Book
Enclosing instance The outer object an inner object belongs to the java book for ch1
outer.new Inner() Creates an inner object linked to outer java.new Chapter("Loops")
Outer.this Inside an inner class, the outer object Book.this.title
Static nested class A nested class declared static; no outer object needed static class Result
Anonymous class A class with no name, declared and created once new Discount() { ... };
Local class A named class declared inside a method class Counter in main
Effectively final A local variable that is never reassigned int rate = 10; never changed
Main$1 The compiler's name for the first anonymous class in Main diwali.getClass().getName()
Encapsulation Keeping fields private and controlling access to them private String title
Interface A list of methods a class promises to have interface Discount
Lambda (preview) A shorter way to write a one-method anonymous class (episode 36) price -> price * 0.9

Summary

  • A class can be declared inside another class: a nested class.
  • Inner class: tied to one outer object, can use its private fields; create it with outer.new Inner(); reach the outer object with Outer.this.
  • Static nested class: no outer object; new Outer.Nested(); uses only static members of the outer class. Prefer it when the link isn't needed.
  • Anonymous class: declare + create a one-time object in one expression, ending with };. javac names it Main$1.
  • Local variables used inside anonymous/local classes must be effectively final.
  • Next: a status that can only be AVAILABLE, ISSUED or LOST, and data classes in one line. Episode 24: enums and records.