Working with Nested and Inner Classes
1. Defining Static Nested Classes
Example: Static nested
public class Outer {
static class Helper {
void run() { System.out.println("helper"); }
}
}
Outer.Helper h = new Outer.Helper();
| Aspect | Detail |
|---|---|
| Outer instance | Not required |
| Access | Outer's static members only |
| Use case | Logical grouping, builders, helper types |
2. Defining Non-Static Inner Classes
| Aspect | Detail |
|---|---|
| Outer instance | Required (implicit reference) |
| Construction | outer.new Inner() |
| Access | All outer members (incl. private) |
| Static members | Allowed since Java 16 |
3. Creating Local Classes
Example: Local class
void process(List<String> items) {
class Counter { int n = 0; void inc() { n++; } }
Counter c = new Counter();
items.forEach(s -> c.inc());
}
| Aspect | Detail |
|---|---|
| Scope | Block where declared |
| Access | Effectively final local vars |
4. Creating Anonymous Classes
Example: Anonymous class
Runnable r = new Runnable() {
@Override public void run() { System.out.println("hi"); }
};
| Aspect | Detail |
|---|---|
| No name | Defined and instantiated in one expression |
Has this | Refers to anonymous instance (unlike lambda) |
| Use case | Multiple methods or fields needed (else use lambda) |
5. Accessing Outer Class Members
| From | Access |
|---|---|
| Inner class | All outer members |
| Static nested | Static outer members only |
| Anonymous | Effectively-final locals + outer members |
6. Understanding .this Syntax
Example: Outer.this
class Outer {
int x = 1;
class Inner {
int x = 2;
void show() {
System.out.println(x); // 2
System.out.println(Outer.this.x); // 1
}
}
}
| Form | Meaning |
|---|---|
this | Inner instance |
Outer.this | Enclosing outer instance |
7. Using Inner Classes for Callbacks
| Pattern | Use |
|---|---|
| Listener / observer | Implements callback interface, accesses outer state |
| Iterator | Inner class returning Iterator<T> |
8. Converting Anonymous to Lambda
| Anonymous | Lambda |
|---|---|
new Runnable() { run() {...} } | () -> {...} |
| SAM only | Required for lambda |
this binding | Anonymous: self; Lambda: enclosing |
9. Understanding Nested Class Use Cases
| Type | When to use |
|---|---|
| Static nested | Builder, helper, no outer state needed |
| Inner | Tight coupling with outer state (e.g., iterator) |
| Local | Scoped helper inside one method |
| Anonymous | Multi-method ad-hoc impl (else lambda) |