Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Object-Oriented Programming

    Nested and Anonymous Classes

    A small helper who only works inside one department doesn't need a desk in the main lobby.

    Chapter 10 of 123 min read

    The Plain Picture#

    A small helper who only works inside one department doesn't need a desk in the main lobby.

    The Real Names#

    KindDeclaredHas access to the outer object?Use
    static nested classstatic class Node { } inside another classnohelper types: a linked list's Node, a map's Entry — the usual choice
    inner classclass Iter { } (non-static) inside anotheryes — each instance is tied to an outer objectiterators that need the outer object's data
    local classinside a methodcan use the method's (effectively final) variablesrare
    anonymous classnew Interface() { ... } right where it's usedsame as localone-off implementations — mostly replaced by lambdas

    Every example program in this file uses static nested classes (static class Student inside public class Oop) so that one file can hold everything.

    Anonymous class — an unnamed class created on the spot:

    Java
    Comparator<String> byLength = new Comparator<String>() {
        // implement the interface right here
        @Override
        public int compare(String a, String b) {
            return Integer.compare(a.length(), b.length());
        }
    };
    
    List<String> names = new ArrayList<>(List.of("Vikram", "Priya", "Al"));
    
    names.sort(byLength);
    
    System.out.println(names); // [Al, Priya, Vikram]

    That's a lot of ceremony for "compare by length". Java 8 lambdas shrink it to names.sort((a, b) -> Integer.compare(a.length(), b.length())); — covered in Modern Java.

    Gotcha: an inner (non-static) class secretly holds a reference to its outer object, which can keep the outer object alive (a memory leak source). Make nested classes static unless they truly need the outer object.

    Check yourself

    2 questions
    1

    Static nested vs inner class — what's the difference?

    Show answer

    An inner class instance is tied to (and holds a reference to) an outer object; a static nested class isn't.

    2

    What is an anonymous class, and what mostly replaced it?

    Show answer

    A class with no name, defined and instantiated in one expression; lambdas replaced most uses.