Reading history

Java Inner, Nested and Anonymous Classes

6 min read 0 views

Learn Java nested classes: inner classes, static nested classes, local classes and anonymous classes, with how they compare to lambdas and capture variables.

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!
  • Cursor is an inner class: every Cursor object is tied to one Playlist object and can read its private fields songs and title directly.
  • Because of that link, you create it through an outer object: road.new Cursor(). This is how many collections build their iterators.
  • Stats is 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 read Playlist‘s private members when given an object.
  • Shout is a local class: declared inside main and 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 implements Discount. 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 Predicate uses the local variable minLength. 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

KindDeclaredNeeds an outer object?Typical use
Static nestedIn a class, with staticNoBuilders, helper types, nodes in a linked list
InnerIn a class, without staticYesIterators and views over the outer object
LocalInside a methodYes, if the method is not staticA helper used only in that method
AnonymousIn an expressionYes, if declared in instance codeOne-off listeners, comparators, callbacks

Common Mistakes

  1. Trying new Inner() from a static method, which fails because there is no outer object. Use outer.new Inner() or make the class static.
  2. Changing a local variable that an anonymous class or lambda uses, which causes “variable must be final or effectively final”.
  3. Writing long anonymous classes inside method calls. Give the class a name, or use a lambda.
  4. Confusing this: inside an anonymous class, this is the anonymous object. Write Outer.this to 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.

Next: Java equals(), hashCode() and toString().

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *