DEV Community

Cover image for Why in older Java non-static inner classes could not have static members?
Mani
Mani

Posted on

Why in older Java non-static inner classes could not have static members?

Before Java 16
Let's understand this with an example

class Outer {
     class Inner {
         // Outer outer;
         static int count = 5; // Not allowed
     }
 }
Enter fullscreen mode Exit fullscreen mode

Now let's look at the main method:

Outer o1 = new Outer();
Outer o2 = new Outer();
Inner i1 = o1.new Inner();
Inner i2 = o2.new Inner()
Enter fullscreen mode Exit fullscreen mode

If i1.count = 5, then what should i2.count be?
The confusion is that count could be associated with o1, or with o2, or with both of them.

Now consider these possibilities:

  • If every Outer instance (o1 and o2) has its own separate count, then it is no longer truly static, because static members are supposed to be shared.
  • If there is only one count shared between both o1 and o2, then the Inner class doesn't really depend on a specific Outer object, which contradicts the nature of a non-static inner class.

To avoid this confusion, Java decided that non-static inner classes cannot contain static fields or static methods.

How is an Inner Class Related to the Outer Class?
-->Every object of a non-static inner class contains a hidden reference to the outer class object that created it.
Conceptually, it looks something like this

class Inner {
   Outer outer; // hidden reference
}
Enter fullscreen mode Exit fullscreen mode

In the earlier example, Java automatically maintains this reference internally, so you don't need to write it yourself.

One Exception: static final
Before Java 16, Java allowed static final constants inside non-static inner classes:

class Outer {
   class Inner {
       static final int COUNT = 5; // Allowed
       static int count = 0;       // Not allowed
    }
}
Enter fullscreen mode Exit fullscreen mode

This was allowed because static final primitive constants are compile-time constants. They don't behave like regular static variables and are often inlined directly into the bytecode by the compiler.
Therefore, before Java 16, a non-static inner class could contain static final compile-time constants, but it could not contain ordinary static fields or static methods.

Top comments (0)