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 it Yourself ยป
    JavaScript
    // ๐Ÿ’ก 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 it Yourself ยป
    JavaScript
    // ๐Ÿ’ก 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

    TypeAccess Outer?Use Case
    Non-static innerโœ… YesTightly coupled helper (Node in LinkedList)
    Static nestedโŒ NoIndependent helper (Builder, Result)
    Local classโœ… Effectively final varsMethod-scoped logic
    Anonymous classโœ… Effectively final varsOne-off โ†’ prefer lambda

    Try It: Iterator Pattern with Inner Class

    Build a custom collection with an inner class iterator

    Try it Yourself ยป
    JavaScript
    // ๐Ÿ’ก 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

    โŒ
    Memory leak with non-static inner class: Inner classes hold an implicit outer reference. Use static nested classes to avoid this.
    โŒ
    Using anonymous class when lambda works: For functional interfaces, prefer a lambda โ€” shorter and better optimized.
    โŒ
    Modifying local variables from inner class: Captured variables must be effectively final. Use an array or AtomicInteger as a workaround.

    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

    TypeAccess Outer?Use Case
    Non-static innerโœ… YesNode in LinkedList
    Static nestedโŒ NoBuilder, Result
    Local classโœ… Final varsMethod helpers
    Anonymous โ†’ Lambdaโœ… Final varsOne-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.

    Previous

    Cookie & Privacy Settings

    We use cookies to improve your experience, analyze traffic, and show personalized ads. You can manage your preferences below.

    By clicking "Accept All", you consent to our use of cookies for analytics and personalized advertising. You can customize your preferences or reject non-essential cookies.

    Privacy Policy โ€ข Terms of Service