0

The official documentation says it is not possible, but it is getting created. How?

As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.

// outer class
class OuterClass
{ 
    
    // nested class
     class StaticNestedClass
    {
        static int a;
        static void hi(){
            System.out.println("inside hi");
        }
        void display()
        {
            a = 9;
            
            System.out.println("inner a = " + a);
            
            hi();
        
        }
    }
}

// Driver class
public class StaticNestedClassDemo
{
    public static void main(String[] args)
    {
        OuterClass outer = new OuterClass();
        OuterClass.StaticNestedClass inner = outer.new StaticNestedClass();
        // all these works
        inner.hi();
        OuterClass.StaticNestedClass.hi();
        
    }
}
khelwood
  • 55,782
  • 14
  • 81
  • 108
  • 3
    Does this answer your question? [Why does Java prohibit static fields in inner classes?](https://stackoverflow.com/questions/1953530/why-does-java-prohibit-static-fields-in-inner-classes) Java 16 has lifted this restriction – knittl Oct 13 '22 at 08:19
  • For quoted material, please link to the source. – khelwood Oct 13 '22 at 08:22
  • the restriction was removed in Java 16 by [JEP 395](https://openjdk.org/jeps/395) - Also in the Java Language Specification [JLS 8.1.3](https://docs.oracle.com/javase/specs/jls/se16/html/jls-8.html#jls-8.1.3-130): "*All of the rules that apply to nested classes apply to inner classes. In particular, an inner class may declare and inherit static members (§8.2), and declare static initializers (§8.7), even though the inner class itself is not static.*" – user16320675 Oct 13 '22 at 10:10
  • Thanks @user16320675 too, I was looking at java 8 documentation. The link you provided is really good. – Bharat Purwar Oct 14 '22 at 09:15

0 Answers0