Search code examples
javaclassstaticinner-classes

Why can't we have static method in a (non-static) inner class (pre-Java 16)?


Why can't we have static method in a non-static inner class?

public class Foo {
    class Bar {
        static void method() {} // Compiler error
    }
}

If I make the inner class static it works. Why?

public class Foo {
    static class Bar { // now static
        static void method() {}
    }
}

In Java 16+, both of these are valid.


Solution

  • Because an instance of an inner class is implicitly associated with an instance of its outer class, it cannot define any static methods itself. Since a static nested class cannot refer directly to instance variables or methods defined in its enclosing class, it can use them only through an object reference, it's safe to declare static methods in a static nested class.