Java Notes
Complete guide to inner classes in Java — member inner classes, static nested classes, local inner classes, and when to use each type for better encapsulation and code organization.
An inner class is a class defined inside another class. Java supports four types of nested classes, each with different access rules and use cases. Inner classes are powerful for encapsulating helper types that only make sense in the context of their enclosing class.
Types of Nested Classes
| Type | Declared | Has access to outer instance? | Use case |
|---|---|---|---|
| Member Inner Class | Inside class body | ✅ Yes | Tightly coupled helper |
| Static Nested Class | Inside class with static | ❌ No | Independent helper |
| Local Inner Class | Inside a method | ✅ Yes + local vars | One-method helper |
| Anonymous Inner Class | Inline (no name) | ✅ Yes + local vars | One-time implementation |
1. Member Inner Class
A non-static class defined inside another class. It has access to ALL members of the outer class, including private:
LinkedList [4]: 5 -> 10 -> 20 -> 30 -> null Iterating: 5 10 20 30
Creating a Member Inner Class Object
// From outside the outer class:
LinkedList list = new LinkedList();
LinkedList.Iterator iter = list.iterator(); // Via factory method (preferred)
LinkedList.Iterator iter2 = list.new Iterator(); // Direct instantiation (less common)2. Static Nested Class
A nested class with static modifier. It does NOT have access to the outer class's instance members:
Connected to: jdbc:mysql://localhost:3306/myapp [pool=10, timeout=5000ms] Executing on jdbc:mysql://localhost:3306/myapp: SELECT * FROM users
3. Local Inner Class
Defined inside a method — limited scope, can access outer class members and effectively final local variables:
public class ReportGenerator {
private String companyName = "TechCorp";
public void generateReport(String[] data, String reportType) {
// Local inner class — exists only within this method
class ReportFormatter {
private String header;
ReportFormatter(String header) {
this.header = header;
}
void printReport() {
System.out.println("=== " + header + " ===");
System.out.println("Company: " + companyName); // Accesses outer field
System.out.println("Type: " + reportType); // Accesses method parameter
for (String item : data) {
System.out.println(" • " + item);
}
System.out.println("==================");
}
}
ReportFormatter formatter = new ReportFormatter("Q4 Report");
formatter.printReport();
}
}
public class Main {
public static void main(String[] args) {
ReportGenerator gen = new ReportGenerator();
gen.generateReport(
new String[]{"Revenue: $1.2M", "Growth: 15%", "New Clients: 23"},
"Quarterly Summary"
);
}
}=== Q4 Report === Company: TechCorp Type: Quarterly Summary • Revenue: $1.2M • Growth: 15% • New Clients: 23 ==================
Member Inner vs Static Nested — When to Use
public class Outer {
private int outerField = 42;
// MEMBER inner class — needs outer instance
class Inner {
void accessOuter() {
System.out.println("Outer field: " + outerField); // ✅ Can access
System.out.println("Outer this: " + Outer.this); // ✅ Has reference
}
}
// STATIC nested class — independent
static class StaticNested {
void tryAccessOuter() {
// System.out.println(outerField); // ❌ Cannot access!
// System.out.println(Outer.this); // ❌ No outer reference!
System.out.println("I'm independent of any Outer instance");
}
}
}Use Member Inner Class When:
- The inner class needs access to the outer class's instance state
- The inner class logically belongs to a specific instance
- Example: Iterator for a collection
Use Static Nested Class When:
- The inner class is logically related but doesn't need outer state
- You want it to be instantiated independently
- Example: Builder, Configuration, Node (in some cases)
Real-World Pattern: Builder with Static Nested Class
POST https://api.example.com/users [headers=2, timeout=5000ms]
Body: {"name": "Alice", "age": 30}Common Mistakes
- Trying to instantiate member inner class without outer:
``java // Inner inner = new Inner(); // ❌ Needs an outer instance Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); // ✅ ``
- Memory leak with inner classes:
``java // Member inner class holds a reference to outer class // If inner lives longer than outer, outer can't be garbage collected! ``
- Modifying local variables in local inner class:
``java int count = 0; class Local { void increment() { count++; // ❌ Must be effectively final! } } ``
- Using member inner class when static would work:
``java // If the inner class doesn't use outer's instance fields, // make it static to avoid carrying an unnecessary reference. ``
Best Practices
- Use static nested for Builder pattern and configuration classes
- Use member inner classes for iterators and event handlers
- Make inner classes
privateunless external access is needed - Prefer static nested over member inner to avoid hidden references
- Keep inner classes small — if it grows large, extract to top-level
- Watch for memory leaks with non-static inner classes in Android/long-lived contexts
Interview Questions
Q1: What is the difference between inner class and static nested class? Inner class has implicit reference to outer instance (can access instance members). Static nested class does not (independent, accessed like a regular class).
Q2: Can an inner class access private members of the outer class? Yes. Member inner classes can access ALL members (including private) of the enclosing class.
Q3: Can we have a static method in a member inner class? No (prior to Java 16). Only static nested classes can have static members. Java 16+ relaxes this rule.
Q4: Why does Java allow inner classes? For better encapsulation and logical grouping. Helper classes that only make sense in the context of another class can be nested inside it.
Q5: What is the hidden reference in member inner classes? Every member inner class instance holds an implicit reference to its enclosing outer class instance. This is how it accesses outer members.
Q6: How do you access the outer class's this from an inner class? Use OuterClassName.this to get the outer class instance reference.
Q7: Can a local inner class access local variables? Only if they are effectively final (not modified after initialization). This is because the inner class may outlive the method, and local variables are on the stack.
Q8: What is the memory implication of non-static inner classes? Each non-static inner class instance holds a hidden reference to its outer class instance. This means the outer object cannot be garbage collected as long as the inner class instance exists. This can cause memory leaks, especially in Android development with Activity references.
Q9: Can an inner class extend another class or implement an interface? Yes. Inner classes are full classes — they can extend any class, implement interfaces, be abstract, or be final. class Outer { class Inner extends SomeClass implements SomeInterface { } } is perfectly valid.
Q10: What is a local inner class? When is it used? A local inner class is defined inside a method body. It's visible only within that method. It can access the enclosing method's local variables only if they're effectively final. Use case: when you need a class for a one-time purpose within a specific method.
Q11: How do you instantiate a non-static inner class from outside the outer class? You need an outer class instance first: Outer outer = new Outer(); Outer.Inner inner = outer.new Inner();. The new keyword is used on the outer instance because the inner class needs a reference to its enclosing object.
Q12: What is the difference between inner class and composition? Inner classes have privileged access to the outer class's private members and exist within the outer class's scope. Composition (class Car { private Engine engine; }) creates a has-a relationship between independent classes with no special access privileges.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Inner Class in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, oops, inner, class
Related Java Master Course Topics