Nested, Inner & Anonymous Classes — Classes Inside Classes

Nested, Inner ও Anonymous Class — ক্লাসের ভেতরে ক্লাস

Read: ~30 min Advanced 5 practice problems Live code runner

1. Four Flavours of Nested Class

Java lets you declare a class inside another class. There are four distinct kinds, each with its own rules:

  • Static nested class — a normal class that happens to live inside another.
  • Inner class (non-static) — an instance of it is always attached to an instance of the enclosing class.
  • Local class — declared inside a method, visible only in that method.
  • Anonymous class — a one-shot class with no name, declared right where it is instantiated.
Java-তে class-এর ভেতরে class চার ধরনের হতে পারে। Static nested — সাধারণ class, শুধু অন্য class-এর ভেতরে রাখা। Inner — প্রতিটি instance outer-এর একটি instance-এর সাথে সংযুক্ত। Local — method-এর ভেতরে declared, শুধু সেই method-এ দৃশ্যমান। Anonymous — নামহীন, যেখানে instantiate সেখানেই declared।

2. Static Nested Class — Namespacing

The static nested class is the simplest and most common. Use it when a helper class is meaningful only in the context of its outer class but does not need access to outer-instance state.

Main.java
class Order {
    int id;
    Order(int id) { this.id = id; }

    // static nested — can be instantiated without an Order instance
    static class Line {
        String item; int qty;
        Line(String item, int qty) { this.item = item; this.qty = qty; }
        @Override public String toString() { return qty + " × " + item; }
    }
}

class Main {
    public static void main(String[] args) {
        Order.Line l = new Order.Line("Hilsa", 2);
        System.out.println(l);
    }
}

3. Inner (Non-Static) Class — Tied to an Instance

An inner class implicitly holds a reference to its enclosing instance. It can freely access the outer instance's fields — including private ones. You cannot create one without an outer instance first.

Main.java
class Library {
    private String branch = "Dhanmondi Branch";

    class Card {                 // inner — no 'static' keyword
        void show() { System.out.println("Card issued at " + branch); }
    }
}

class Main {
    public static void main(String[] args) {
        Library lib  = new Library();
        Library.Card c = lib.new Card();   // funny but real syntax
        c.show();
    }
}
Memory gotcha: every inner-class instance keeps the outer instance alive. In long-lived apps (Android!) this is a classic source of memory leaks. Make nested classes static unless you really need the outer reference.

4. Anonymous Classes & the Lambda Replacement

Before Java 8, the idiom for "one-off implementation of an interface" was the anonymous class. Java 8's lambda made most uses dramatically shorter — but anonymous classes are still useful when you need multiple methods, instance state, or a named constructor call.

Main.java
import java.util.Comparator;

class Main {
    public static void main(String[] args) {

        // (a) Anonymous class — old style
        Comparator<String> byLenOld = new Comparator<String>() {
            @Override public int compare(String a, String b) {
                return a.length() - b.length();
            }
        };

        // (b) Lambda — modern equivalent
        Comparator<String> byLenNew = (a, b) -> a.length() - b.length();

        System.out.println(byLenOld.compare("Rahim", "Sadia"));
        System.out.println(byLenNew.compare("ABC", "ABCDE"));
    }
}
Lambda এসে বেশিরভাগ anonymous class-এর কাজ সহজ হয়ে গেছে — কিন্তু যখন একাধিক method override করতে হবে, instance state লাগবে, বা নির্দিষ্ট constructor call দরকার — তখন anonymous class এখনো কাজে আসে।

5. Which to Use When

ScenarioBest choice
Helper that does not need the outer instancestatic nested class
Iterator or node tightly bound to outer stateInner class
Small helper used in exactly one methodLocal class (or better, a lambda)
One-off single-method interfaceLambda
One-off but multiple methods or state neededAnonymous class
Immutable data carrierrecord (nested or top-level)
নিয়ম: static nested (namespacing), inner (outer instance state দরকার), local (একটি method-এর মধ্যে শুধু), anonymous (এক-শটের implementation, একাধিক method হলে), আর single-method interface হলে lambda।

6. Vocabulary (শব্দভাণ্ডার)

TermMeaningবাংলায়
Static nestedNested class with static modifier; independent of outer instance.Outer instance ছাড়াই বানানো যায়।
Inner classNon-static nested; holds a hidden reference to outer.Outer instance-এর সাথে সংযুক্ত।
Local classDeclared inside a method body.Method-এর ভেতরে ঘোষিত।
Anonymous classUnnamed class declared inside an expression.নামহীন class, expression-এর মধ্যে ঘোষিত।
CapturingInner/local/anonymous class uses variables from outside.বাইরের variable ব্যবহার করা।
Effectively finalNot marked final but never reassigned — required for capture.Final marked নয় তবু পুনঃনিয়োগিত নয় — capture-এর শর্ত।

7. Practice Problems

  1. Write an outer class BankAccount with a static nested Transaction record. Create a transaction and print it.
    BankAccount class-এ static nested Transaction record রাখুন। একটি transaction তৈরি করে print করুন।
    ✨ Show Answer
    Main.java
    class BankAccount {
        static record Transaction(String kind, double amount) {}
    }
    class Main {
        public static void main(String[] args) {
            BankAccount.Transaction t = new BankAccount.Transaction("DEPOSIT", 2500);
            System.out.println(t);
        }
    }
  2. Use an anonymous class to implement Runnable and run it on a new thread. Print "work done" from inside.
    Anonymous class দিয়ে Runnable implement করে নতুন thread-এ চালান — ভেতর থেকে "work done" print করুন।
    ✨ Show Answer
    Main.java
    class Main {
        public static void main(String[] args) throws InterruptedException {
            Runnable r = new Runnable() {
                @Override public void run() { System.out.println("work done"); }
            };
            Thread t = new Thread(r);
            t.start();
            t.join();
        }
    }
  3. Why is it usually safer to mark a nested helper class static? Two sentences.
    Nested helper class-কে static করা কেন সাধারণত নিরাপদ — দুই বাক্যে।
    ✨ Show Answer

    Answer: A non-static inner class carries an implicit reference to its enclosing instance — that keeps the outer object alive for as long as any inner instance is reachable, a classic memory-leak pattern (especially in long-running apps and Android). If the nested class does not actually need outer state, making it static removes the reference entirely.

    Non-static inner class outer instance-এর hidden reference ধরে রাখে — এটি memory leak-এর কারণ হতে পারে। Outer state না লাগলে static করে দিলে এই reference থাকে না।

  4. Replace this anonymous class with a lambda: Runnable r = new Runnable() { public void run() { System.out.println("hi"); } };
    এই anonymous class-কে lambda দিয়ে প্রতিস্থাপন করুন।
    ✨ Show Answer
    Main.java
    class Main {
        public static void main(String[] args) {
            Runnable r = () -> System.out.println("hi");
            r.run();
        }
    }
  5. When would a lambda NOT be able to replace an anonymous class? Give one specific reason.
    কোন ক্ষেত্রে lambda দিয়ে anonymous class প্রতিস্থাপন সম্ভব নয় — একটি নির্দিষ্ট কারণ দিন।
    ✨ Show Answer

    Answer: A lambda only works for a functional interface (exactly one abstract method). If the target type has multiple abstract methods (or is an abstract class rather than an interface), you must use an anonymous class. Also, anonymous classes can declare their own instance fields and use this to mean themselves — a lambda's this means the enclosing instance.

    Lambda শুধু functional interface-এর জন্য কাজ করে (একটিই abstract method)। একাধিক abstract method বা abstract class হলে anonymous class দরকার।

Summary — Module 18

Java gives you four ways to nest a class. Static nested classes are just namespaced helpers. Inner classes are implicitly tied to an outer instance — powerful but a memory-leak risk. Local classes are private helpers inside a method. Anonymous classes are unnamed one-shot implementations. Since Java 8, lambdas have replaced most anonymous classes for single-method interfaces — shorter, clearer, and with different this semantics. Reach for an anonymous class only when you need multiple overrides or extra instance state.

Java-তে class-এর ভেতরে class চার ধরনের। Static nested সাধারণ namespaced helper। Inner outer instance-এর সাথে সংযুক্ত — শক্তিশালী কিন্তু memory-leak-এর ঝুঁকি। Local method-এর ভেতরের private helper। Anonymous নামহীন এক-শটের implementation। Java 8-এর পর single-method interface-এর জন্য lambda বেশিরভাগ সময় সঠিক। একাধিক override বা instance state দরকার হলে তখন anonymous class।

Next Module → equals, hashCode ও toString — contract ঠিকঠাক পালন করা।