Course contentsShow
← Java
Lesson 631 of 2,87015. Nested and Inner ClassesFree lesson

Memory Implications of Inner Classes

Recognize that inner class instances increase memory usage due to the implicit outer reference and potential leaks.

Memory Implications of Inner Classes

What You'll Learn

You'll understand how inner classes consume more memory than you might expect and how to avoid accidentally keeping objects alive longer than necessary.

The Hidden Cost of the Implicit Outer Reference

Every inner class instance carries an invisible reference to its outer class instance—it's how the inner object can access outer fields and methods. This reference takes up memory, but more importantly, it prevents the outer object from being garbage collected as long as the inner object is still alive.

Think of it like a child holding their parent's hand. Even if the parent wants to leave the park (be garbage collected), they can't—because the child (inner instance) is still holding on.

The Memory Leak Trap

This becomes a problem when inner class instances outlive their intended scope:

public class DataProcessor {
    private byte[] largeData = new byte[10_000_000]; // 10 MB
    
    public Runnable createTask() {
        return new Runnable() {
            public void run() {
                System.out.println("Task running");
            }
        };
    }
}

Here, the Runnable inner class instance holds a reference to the entire DataProcessor object—including that 10 MB array—even though the task doesn't use it at all! If you store that Runnable in a long-lived collection, the DataProcessor can never be freed.

The Static Nested Class Solution

If your inner class doesn't need access to outer instance members, make it static:

public static class Task implements Runnable {
    public void run() {
        System.out.println("Task running");
    }
}

No implicit outer reference means no memory leak risk.

Key Takeaway: Inner class instances hold an implicit reference to their outer object, increasing memory usage and potentially causing leaks if the inner instance outlives its expected scope. Use static nested classes when you don't need outer access.