Nested Classes

⭐ Interview Importance: MEDIUM
⏱️ Revision Time: 5 min

TL;DR

  • A Nested Class is simply a class declared within another class.
  • They are used to logically group classes that are only used in one place, increasing encapsulation and producing more readable code.
  • They are broadly categorized into Static Nested Classes and Non-Static Nested Classes (Inner Classes).

Concept

Sometimes a class is so intimately tied to another class that it makes no sense for it to exist anywhere else in the project.

For example, java.util.Map.Entry is a nested interface. An “Entry” (a key-value pair) only makes sense within the context of a “Map”. By putting Entry inside Map, we logically group them together and avoid polluting the global namespace with a generic Entry class that might conflict with other libraries.

Types of Nested Classes

  1. Static Nested Class: Like a regular top-level class, but nested for packaging convenience. It does not have access to the outer class’s instance variables.
  2. Inner Class (Non-static): Is tied to a specific instance of the outer class. It has full access to the outer class’s private instance variables.
  3. Local Class: Defined inside a method block.
  4. Anonymous Class: Defined and instantiated on the fly without a name.

Examples

public class OuterClass {
    
    private String secret = "Outer Secret";
    private static String staticSecret = "Static Secret";

    // 1. Static Nested Class
    static class StaticNested {
        void print() {
            // Can access static members of Outer
            System.out.println(staticSecret);
            // ERROR: Cannot access non-static 'secret'
        }
    }

    // 2. Inner Class
    class Inner {
        void print() {
            // Can magically access private instance members of Outer!
            System.out.println(secret); 
        }
    }
}

Interview Questions

Q: Why do Inner Classes cause Memory Leaks?
A: An Inner Class (non-static) implicitly holds a hidden reference to the specific instance of the Outer Class that created it (accessed via OuterClass.this). If you pass an instance of the Inner Class to another part of the system (like an event listener cache) and it lives a long time, the Garbage Collector cannot delete the Outer Class instance, because the hidden reference inside the Inner Class keeps it alive. This is a very common source of memory leaks in Android and UI programming.

Q: When should you use a Static Nested Class vs an Inner Class?
A: Always default to a Static Nested Class unless you absolutely require access to the outer class’s instance variables. Static nested classes do not hold a hidden reference to the outer instance, meaning they consume less memory, are faster to instantiate, and completely eliminate the risk of the memory leak described above.