Why can't inner classes declare static members?

前端 未结 5 478
清酒与你
清酒与你 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:11

    Basically just an arbitrary decision. there's no reason it couldn't be supported, but there is also not really any good reason to support it. just declare the static field in the outer class.

    also, that quote may not be entirely correct: i believe you can declare a static serialVersionUID in an inner class.

    0 讨论(0)
  • 2021-02-01 18:21

    Why can't inner classes declare static members?

    The inner class is contained in the instance area of ​​the outer class. Therefore, within the inner class, it is not allowed to declare static members. On the other hand, the static inner class is contained in the static area of ​​the outer class. Thus, it is only allowed to declare static members and not instance members.

    0 讨论(0)
  • 2021-02-01 18:26

    Because the Java Language Specification says so:

    An inner class is a nested class that is not explicitly or implicitly declared static. Inner classes may not declare static initializers (§8.7) or member interfaces. Inner classes may not declare static members, unless they are compile-time constant fields (§15.28).

    As for why it was specified that way, I do not know. My guess is that inner classes were designed as small helper classes that should be very limited in complexity.

    0 讨论(0)
  • 2021-02-01 18:28

    An inner class may not declare static fields unless they are compile-time constants. Hence, if you declare the static field as final it will work.

    class Foo {
        class Test {
           final static int i = 10;
        }
    }
    

    will compile and run perfectly

    static fields can only be declared in static or top-level types. Hence, a (pure) static variable can be declared only in a static class.

    0 讨论(0)
  • 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;
    
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题