Why can't inner classes declare static members?

前端 未结 5 525
清酒与你
清酒与你 2021-02-01 17:36

The Java Tutorial says that since an inner class is associated with an instance of the enclosing class, it (the inner class) cannot define any static members itself.

It\

5条回答
  •  青春惊慌失措
    2021-02-01 18:35

    That would result in a conflict of interest to have a static member variable inside an inner class. Generally speaking, an inner class needs to have an object instance of the outer or enclosing class before it may be instantiated. A static member variable suggests that you don't even need an object instance for that particular class, the inner class in this case, but that class the inner class is dependent upon and can only coexist along with the outer class instance. Do you see where the conflict of interest arises in the argument? However, you can make a static member variable inside an inner class by declaring the inner class as static which means the inner class no longer needs to coexist with an outer class object.

    public class A {
    
       public static class B {
    
           private static JPanel myJPanel;
    
       }
    
    }
    

提交回复
热议问题