In Java, nested classes can be declared with the static keyword. Unlike member inner classes, a **static nested class** behaves like any outer class, meaning it cannot access non-static instance variables of its parent directly. Similarly, Java supports **nested interfaces** declared inside other interfaces or classes.

In this guide, we will trace the access rules of static nested classes and how to implement nested interfaces.

Illustration representing class relationships and static boundaries
Real-World Analogy: Independent Subdivisions

Imagine a corporate company headquarters building:

  • Member Inner Class: An department desk inside the office. It needs an employee badge and can access the private water coolers.
  • Static Nested Class: A separate retail coffee shop renting space in the ground floor lobby. It is physically inside the building, but operates independently. It cannot look at internal company employee profiles.

1. Static Nested Classes

A static nested class can only access static fields of the outer class. You do not need an instance of the outer class to instantiate it:

class StaticNestedClass {
    static int data = 30; // Must be static
    int instanceData = 50;

    static class Nested {
        void msg() {
            System.out.println("Static data is " + data);
            // System.out.println(instanceData); // Compile error!
        }
    }

    public static void main(String args[]) {
        // Instantiate without outer object!
        StaticNestedClass.Nested obj = new StaticNestedClass.Nested();
        obj.msg(); // Prints: Static data is 30
    }
}

2. Static Methods inside Static Nested Classes

If your static nested class contains static methods, you don't even need to instantiate the nested class itself:

class StaticNestedClassWithStaticMethod {
    static int data = 30;

    static class Nested {
        static void msg() { // Static method
            System.out.println("data is " + data);
        }
    }

    public static void main(String args[]) {
        // Direct access! No instantiation needed
        StaticNestedClassWithStaticMethod.Nested.msg();
    }
}

3. Nested Interfaces

An interface can be declared inside another interface or class. These are implicit static members, used to group related interfaces:

// Declared inside an interface
interface Showable {
    void show();

    interface Message { // Implicitly static nested interface
        void msg();
    }
}

class TestNestedInterface1 implements Showable.Message {
    public void msg() {
        System.out.println("Hello nested interface");
    }

    public static void main(String args[]) {
        Showable.Message message = new TestNestedInterface1();
        message.msg();
    }
}

Conclusion

Use static nested classes when the inner class does not depend on instance states of the outer class. Similarly, use nested interfaces to structure tight contracts that are logically grouped together.