Advanced Java: Collections, Generics and More ยท More Language Features

Nested, Inner and Anonymous Classes

Classes inside classes: a static helper, an inner class tied to an outer object, and a one-off anonymous class.

NestedClassesDemo.java

public class NestedClassesDemo {
    private int count = 0;

    static class Helper {                 // static nested: no outer object needed
        static int twice(int n) { return n * 2; }
    }

    class Clicker {                       // inner: belongs to an outer object
        void click() { count++; }         // can use the outer object's fields
    }

    interface Action { String run(); }

    public static void main(String[] args) {
        int t = Helper.twice(21);
        NestedClassesDemo outer = new NestedClassesDemo();
        NestedClassesDemo.Clicker c = outer.new Clicker();
        c.click();
        c.click();
        Action a = new Action() {          // anonymous: a one-off class with no name
            public String run() { return "ran"; }
        };
        System.out.println(t + " " + outer.count + " " + a.run());
    }
}

Step by step

  1. A static nested class is used like any class, through the outer class's name.
  2. twice() has finished, so its variables are gone.
  3. A static nested class is used like any class, through the outer class's name.
  4. Java runs the NestedClassesDemo constructor to set up the new object.
  5. Line runs: public class NestedClassesDemo {.
  6. NestedClassesDemo() has finished, so its variables are gone.
  7. outer is created on the stack and points to a new NestedClassesDemo on the heap: {count: 0}.
  8. outer.new Clicker(): an inner object is always tied to an outer object.
  9. NestedClassesDemo$Clicker() has finished, so its variables are gone.
  10. outer.new Clicker(): an inner object is always tied to an outer object.
  11. Java calls click(). It gets its own variables on the stack.
  12. click() changes count, which belongs to the outer object.
  13. Java calls click(). It gets its own variables on the stack.
  14. click() has finished, so its variables are gone. count in the NestedClassesDemo that outer points to changes from 1 to 2.
  15. An anonymous class: declared and created in one go, with no name.
  16. NestedClassesDemo$1() has finished, so its variables are gone.
  17. The value it returned, {}, is stored in a.
  18. Java calls run(). It gets its own variables on the stack.
  19. run() has finished, so its variables are gone.
  20. It prints 42 2 ran.
  21. 42, 2 and "ran": three kinds of class inside one file.