Advanced Java: Collections, Generics and More ยท More Language Features
Classes inside classes: a static helper, an inner class tied to an outer object, and a one-off anonymous class.
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());
}
}twice() has finished, so its variables are gone.NestedClassesDemo constructor to set up the new object.public class NestedClassesDemo {.NestedClassesDemo() has finished, so its variables are gone.outer is created on the stack and points to a new NestedClassesDemo on the heap: {count: 0}.NestedClassesDemo$Clicker() has finished, so its variables are gone.click(). It gets its own variables on the stack.click(). It gets its own variables on the stack.click() has finished, so its variables are gone. count in the NestedClassesDemo that outer points to changes from 1 to 2.NestedClassesDemo$1() has finished, so its variables are gone.a.run(). It gets its own variables on the stack.run() has finished, so its variables are gone.42 2 ran.