Why can't inner classes declare static members?

前端 未结 5 480
清酒与你
清酒与你 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条回答
  •  梦毁少年i
    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.

提交回复
热议问题