Lesson content
Read, practise, then check your understanding
A non-static member inner class carries an enclosing-instance reference and can access its members. A static nested class behaves like an ordinary class scoped inside another and is preferable when no outer instance is needed.
Four nested forms
class Cache {
static final class Entry { String key; Object value; }
final class Cursor {
int position;
int ownerSize() { return Cache.this.size(); }
}
int size() { return 0; }
}
Runnable task = new Runnable() {
@Override public void run() { System.out.println("done"); }
};
Local classes are named inside a block; anonymous classes provide a one-off subtype expression. Both can capture final or effectively final locals. Lambdas are usually clearer for functional interfaces but differ in this, identity, and generated behavior. Avoid accidental retention: a long-lived inner object can keep its entire outer object alive. Use nesting to hide implementation details and express tight ownership, not merely to shorten names.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.