AdvancedOOP Concepts ยท Lesson 17 of 18 ยท Updated ยท
Nested, Inner and Anonymous Classes in Java โ and When a Lambda Is Better
Some classes only make sense together with another class. A linked list's Node, a map's Entry and a builder's Builder are examples. Java lets you write such a class inside another class. These are called nested classes, and they come in four kinds. Interviewers ask about the differences ("static nested vs inner class?", "anonymous class vs lambda?"), and you will see all four in real Java code.
1. Why put a class inside another class?
- Grouping:
Hostel.Roomsays clearly that a room belongs to the hostel idea. - Encapsulation: a nested class can be
private, so no other code can use it. It can also read the outer class'sprivatemembers. - Less clutter: small helper classes do not need their own file.
2. Static nested class
A static nested class is declared with static inside another class. It behaves like a normal top-level class that just lives in the outer class's namespace. It does not need an object of the outer class, and it can access the outer class's private static members.
class Hostel {
private static int roomsBuilt = 0;
static class Room {
int number;
Room(int number) {
this.number = number;
roomsBuilt++; // allowed: private static member of the outer class
}
}
static int roomsBuilt() { return roomsBuilt; }
}
public class Main {
public static void main(String[] args) {
Hostel.Room r1 = new Hostel.Room(101); // no Hostel object needed
Hostel.Room r2 = new Hostel.Room(102);
System.out.println("Rooms: " + r1.number + ", " + r2.number);
System.out.println("Built: " + Hostel.roomsBuilt());
}
}
Rooms: 101, 102
Built: 2
The Builder pattern (Pizza.Builder) and the private Node class inside java.util.LinkedList are static nested classes. Default choice: if a nested class does not need the outer object's fields, make it static.
3. Inner class (non-static)
An inner class is a nested class without static. Every inner object is tied to one outer object and can read that object's fields directly โ even private ones. Because of this link, you create it through an outer object with the unusual syntax outer.new Inner(...).
class Bank {
private String name;
Bank(String name) { this.name = name; }
class Account {
private int balance;
Account(int balance) { this.balance = balance; }
String describe() {
return name + " account, balance " + balance; // reads the outer object's field
}
}
}
public class Main {
public static void main(String[] args) {
Bank green = new Bank("Green Bank");
Bank river = new Bank("River Bank");
Bank.Account a = green.new Account(500);
Bank.Account b = river.new Account(900);
System.out.println(a.describe());
System.out.println(b.describe());
}
}
Green Bank account, balance 500
River Bank account, balance 900
Both accounts run the same describe() code, but each prints its own bank's name. Java does this by storing a hidden reference to the outer object inside every inner object. You can write it explicitly as Bank.this.name โ useful when an inner field has the same name as an outer one.
That hidden reference has a cost: as long as an inner object is alive, its outer object cannot be garbage-collected. This is one more reason to prefer static nested classes when you do not need the link.
4. Local and anonymous classes
A local class is declared inside a method and can be used only in that method. An anonymous class is a class with no name, declared and instantiated in one expression โ usually to implement an interface once, such as a Comparator.
Both can use local variables of the surrounding method, but only if those variables are effectively final โ never changed after they are first assigned. (The class gets a copy of the value, so Java forbids changes that would make the copy and the original differ.)
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<>(List.of("Ravi", "Asha", "Mohammed", "Jo"));
int minLength = 3; // effectively final: never changed
// anonymous class: implements Comparator once, right here
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
});
System.out.println(names);
// local class: a named helper that exists only inside main
class LengthFilter {
boolean ok(String s) { return s.length() >= minLength; }
}
LengthFilter filter = new LengthFilter();
List<String> kept = new ArrayList<>();
for (String n : names) {
if (filter.ok(n)) kept.add(n);
}
System.out.println(kept);
}
}
[Jo, Ravi, Asha, Mohammed]
[Ravi, Asha, Mohammed]
Ravi stays before Asha because both have 4 letters and Java's list sort is stable (equal items keep their order). If you added minLength++; anywhere in main, the code would no longer compile.
5. Anonymous class or lambda?
Since Java 8, an interface with exactly one abstract method (a functional interface, such as Comparator, Runnable or Predicate) can be implemented with a lambda: (a, b) -> Integer.compare(a.length(), b.length()). It is shorter and usually clearer. But the two are not identical. The biggest difference is what this means:
public class Main {
String label = "Main object";
void run() {
Runnable anon = new Runnable() {
String label = "anonymous object";
@Override
public void run() { System.out.println("anonymous: " + this.label); }
};
Runnable lambda = () -> System.out.println("lambda: " + this.label);
anon.run();
lambda.run();
}
public static void main(String[] args) {
new Main().run();
}
}
anonymous: anonymous object
lambda: Main object
Inside an anonymous class, this is the anonymous object itself. A lambda is not a new object scope, so this means the enclosing Main object.
| Anonymous class | Lambda | |
|---|---|---|
| Works for | Any interface or class (even with several methods), can add fields | Only functional interfaces |
this refers to | The anonymous object | The enclosing object |
| Can keep its own state (fields) | Yes | No |
| Length | Long | Short |
Rule of thumb: use a lambda for a functional interface; use an anonymous class when you need fields, several methods, or to extend a class.
Common mistakes
- Writing
new Bank.Account(500)for an inner class. It needs an outer object:green.new Account(500). - Making a nested class inner (non-static) when it never uses the outer object โ wasted memory and a hidden reference that can delay garbage collection.
- Changing a local variable that an anonymous class, local class or lambda uses. It must be effectively final.
- Expecting
thisinside a lambda to mean the lambda. It means the enclosing object. - Trying to write a lambda for an interface with two abstract methods. Only functional interfaces work.
Quick recap
- Static nested: no outer object needed; default choice for helper classes.
- Inner: tied to one outer object, reads its fields, created with
outer.new Inner(), outer object reachable asOuter.this. - Local: declared in a method; anonymous: no name, declared and created in one expression.
- Local and anonymous classes and lambdas can use only effectively final local variables.
- Prefer a lambda for functional interfaces; in a lambda,
thisis the enclosing object.