Sub topic 1
Java Nested, Inner, and Anonymous Classes
Prerequisites
This chapter assumes you can write and compile basic Java classes, use access modifiers, distinguish instance and static members, and implement interfaces.
Why Nest Classes, and the Four Kinds
A nested class is declared inside another class. Nesting groups helper code with the class that uses it and can limit the helper's visibility.
Java has four common kinds:
| Kind | Has an outer object? | Typical use |
|---|---|---|
| Static nested class | No | Independent helper or builder |
| Inner member class | Yes | Helper tied to one outer object |
| Local class | Yes, when declared in an instance method | Small method-specific helper |
| Anonymous class | Depends on its context | One-time implementation or subclass |
The class kind affects object creation, access to fields, and object lifetime.
Static Nested Classes
A static nested class does not belong to a particular instance of its enclosing class. Create it through the enclosing class name. It can access private members of the enclosing class, but it cannot use an enclosing instance directly.
public class Pizza {
private final String size;
private Pizza(String size) {
this.size = size;
}
public static class Builder {
private String size = "medium";
public Builder size(String size) {
this.size = size;
return this;
}
public Pizza build() {
return new Pizza(size);
}
}
public static void main(String[] args) {
Pizza pizza = new Pizza.Builder().size("large").build();
System.out.println(pizza.size); // large
}
}A builder is often static because building a Pizza does not require an existing Pizza.
Inner Classes and Their Link to an Outer Object
An inner class is a non-static member class. Every inner object is associated with one enclosing object. It can read and update that object's private fields.
public class Counter {
private int count;
public class Incrementer {
public void run() {
count++;
}
}
public static void main(String[] args) {
Counter counter = new Counter();
Counter.Incrementer incrementer = counter.new Incrementer();
incrementer.run();
System.out.println(counter.count); // 1
}
}`Outer.this` and `outer.new Inner()`
Use outer.new Inner() to create an inner object from a specific outer object. Inside the inner class, Outer.this explicitly refers to that enclosing object. This is useful when a parameter or field named this-like data makes the relationship unclear.
Exercise
Which syntax creates an inner member class named Inner for the object outer?
Show answer
outer.new Inner().