Lesson 18 โข Advanced
Inner Classes & Anonymous Classes
Static, non-static, local, and anonymous inner classes explained with practical examples.
๐ Before You Start
You should understand:
- OOP (Lesson 9) โ classes, constructors, methods
- Interfaces (Lesson 11) โ implementing contracts
- Lambdas (Lesson 15) โ functional programming basics
What You'll Learn
- โ Non-static inner classes (member classes)
- โ Static nested classes
- โ Local classes (inside methods)
- โ Anonymous classes and their lambda equivalents
- โ When to use each type of inner class
1๏ธโฃ Types of Inner Classes
๐ก Analogy: Rooms in a House โ A non-static inner class (bedroom) has full access to the house. A static nested class (detached garage) is attached but independent. A local class (tent) is temporary. An anonymous class is like hiring a one-time caterer โ no formal contract.
Memory warning: Non-static inner classes hold an implicit reference to the outer instance. If the inner class outlives the outer (e.g., as a callback), the outer can't be garbage collected โ a common memory leak.
// Non-static inner: holds ref to outer
public class LinkedList {
private class Node { /* can access LinkedList.this */ }
}
// Static nested: independent
public class Calculator {
public static class Result { /* no outer reference */ }
}
// Anonymous โ Lambda (Java 8+)
Runnable task = () -> System.out.println("Running!");Try It: Non-static & Static Inner Classes
Build a LinkedList with inner Node class and a Calculator with static Result
// ๐ก Try modifying this code and see what happens!
// Inner Classes (Simulated)
console.log("=== Non-static Inner Class ===\n");
// 1. LinkedList with inner Node
class LinkedList {
constructor() { this.head = null; this.size = 0; }
createNode(data) { return { data, next: null, list: this }; }
add(data) {
let node = this.createNode(data);
node.next = this.head;
this.head = node;
this.size++;
}
toArray() {
let result = [], current = thi
...2๏ธโฃ Local & Anonymous Classes
Local classes are defined inside a method โ they exist only within that method's scope. Anonymous classes are one-time implementations defined inline, largely replaced by lambdas in modern Java.
// Local class (inside method)
void processData(List<String> data) {
class Validator { boolean isValid(String s) { return s != null; } }
Validator v = new Validator();
data.stream().filter(v::isValid).forEach(System.out::println);
}
// Anonymous class โ lambda
Comparator<String> cmp = (a, b) -> a.length() - b.length();Try It: Anonymous Classes & Lambdas
Compare anonymous class syntax with lambda equivalents
// ๐ก Try modifying this code and see what happens!
// Anonymous Classes & Lambdas (Simulated)
console.log("=== Anonymous Classes ===\n");
// 1. Sorting with anonymous comparators
let employees = [
{ name: "Charlie", age: 30, salary: 70000 },
{ name: "Alice", age: 25, salary: 85000 },
{ name: "Bob", age: 35, salary: 60000 }
];
let sorters = {
byName: (a, b) => a.name.localeCompare(b.name),
byAge: (a, b) => a.age - b.age,
bySalary: (a, b) => b.salary - a.salary
};
conso
...3๏ธโฃ When to Use Each Type
| Type | Access Outer? | Use Case |
|---|---|---|
| Non-static inner | โ Yes | Tightly coupled helper (Node in LinkedList) |
| Static nested | โ No | Independent helper (Builder, Result) |
| Local class | โ Effectively final vars | Method-scoped logic |
| Anonymous class | โ Effectively final vars | One-off โ prefer lambda |
Try It: Iterator Pattern with Inner Class
Build a custom collection with an inner class iterator
// ๐ก Try modifying this code and see what happens!
// Iterator Pattern with Inner Class (Simulated)
console.log("=== Custom Iterator ===\n");
class NumberRange {
constructor(start, end) { this.start = start; this.end = end; }
// Inner iterator class
[Symbol.iterator]() {
let current = this.start;
let end = this.end;
return {
next() {
if (current <= end) return { value: current++, done: false };
return { done:
...4๏ธโฃ Common Mistakes
5๏ธโฃ Pro Tips
๐ก Default to static nested classes unless you specifically need outer instance access.
๐ก The Builder pattern is the classic static nested class use case: new Pizza.Builder().size("L").build()
๐ก In modern Java (8+), anonymous classes are mostly replaced by lambdas except for multi-method interfaces.
๐ Quick Reference
| Type | Access Outer? | Use Case |
|---|---|---|
| Non-static inner | โ Yes | Node in LinkedList |
| Static nested | โ No | Builder, Result |
| Local class | โ Final vars | Method helpers |
| Anonymous โ Lambda | โ Final vars | One-off implementations |
๐ Lesson Complete!
You understand all four types of inner classes and when to use each one!
Next: Exception Handling Architecture โ custom hierarchies, chained exceptions, and error strategies.
Sign up for free to track which lessons you've completed and get learning reminders.