Nested, Inner & Anonymous Classes — Classes Inside Classes
Nested, Inner ও Anonymous Class — ক্লাসের ভেতরে ক্লাস
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.
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.
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.
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();
}
}
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.
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"));
}
}
5. Which to Use When
| Scenario | Best choice |
|---|---|
| Helper that does not need the outer instance | static nested class |
| Iterator or node tightly bound to outer state | Inner class |
| Small helper used in exactly one method | Local class (or better, a lambda) |
| One-off single-method interface | Lambda |
| One-off but multiple methods or state needed | Anonymous class |
| Immutable data carrier | record (nested or top-level) |
6. Vocabulary (শব্দভাণ্ডার)
| Term | Meaning | বাংলায় |
|---|---|---|
| Static nested | Nested class with static modifier; independent of outer instance. | Outer instance ছাড়াই বানানো যায়। |
| Inner class | Non-static nested; holds a hidden reference to outer. | Outer instance-এর সাথে সংযুক্ত। |
| Local class | Declared inside a method body. | Method-এর ভেতরে ঘোষিত। |
| Anonymous class | Unnamed class declared inside an expression. | নামহীন class, expression-এর মধ্যে ঘোষিত। |
| Capturing | Inner/local/anonymous class uses variables from outside. | বাইরের variable ব্যবহার করা। |
| Effectively final | Not marked final but never reassigned — required for capture. | Final marked নয় তবু পুনঃনিয়োগিত নয় — capture-এর শর্ত। |
7. Practice Problems
-
Write an outer class
BankAccountwith a static nestedTransactionrecord. Create a transaction and print it.BankAccountclass-এ static nestedTransactionrecord রাখুন। একটি transaction তৈরি করে print করুন।✨ Show Answer
Main.javaclass 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); } } -
Use an anonymous class to implement
Runnableand run it on a new thread. Print "work done" from inside.Anonymous class দিয়েRunnableimplement করে নতুন thread-এ চালান — ভেতর থেকে "work done" print করুন।✨ Show Answer
Main.javaclass 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(); } } -
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
staticremoves the reference entirely.Non-static inner class outer instance-এর hidden reference ধরে রাখে — এটি memory leak-এর কারণ হতে পারে। Outer state না লাগলে
staticকরে দিলে এই reference থাকে না। -
Replace this anonymous class with a lambda:
Runnable r = new Runnable() { public void run() { System.out.println("hi"); } };এই anonymous class-কে lambda দিয়ে প্রতিস্থাপন করুন।✨ Show Answer
Main.javaclass Main { public static void main(String[] args) { Runnable r = () -> System.out.println("hi"); r.run(); } } -
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
thisto mean themselves — a lambda'sthismeans 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.