Skip to content

Chapter 15 of 37

Inner and Nested Classes

Use member, static nested, local, and anonymous classes with clear lifetimes.

30 minutes 10 quick checksBy Subha Prasad
Lesson 15 of 37Course navigation

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.

Which statement best describes inner class?
Which Java term matches this description: A non-static nested class associated with an enclosing instance.
Which statement best describes static nested class?
Which Java term matches this description: A nested class that does not capture an enclosing instance.
Which statement best describes local class?
Which Java term matches this description: A named class declared inside a block.
Which statement best describes anonymous class?
Which Java term matches this description: An unnamed one-off class expression implementing or extending a type.
Which statement best describes effectively final?
Which Java term matches this description: A local variable assigned once and therefore capturable.

0 of 10 checks passed

Your progress is saved on this device.