Why can't I declare and initialize static variable in inner class? [duplicate]

北慕城南 提交于 2020-01-03 02:40:11

问题


class A is the outer class. Class B is an inner class of A, and class C is an inner class of B.

All three classes declare and initialize one static final variable.

This is the object in class A:

static final Object x = new Object();

class B:

static final Object x1 = new Object();

class C:

static final Object x2 = new Object();

The problem is that the variable in class A compiles fine, but in B and C the variable does not.

Error message:

the field can not be declare static; static field only declared in static and top level type

The String, and int in class B and C doesn't receive an error.

Complete code:

class A {
  static final Object x = new Object();
  static final String s = "s1";
  static final int y = 1;

  class B {
    static final Object x1 = new Object();
    static final String s1 = "s1";
    static final int y1 = 1;

     class C {
      static final Object x2 = new Object();
      static final String s2 = "s1";
      static final int y2 = 1;
     }
  }
}

回答1:


You can't have static fields/method in a regular inner classes, because, inner classes will work only with instance of outer classes.

So, static can't be there with instances.

But they can have compile time constants, check JLS 8.1.3. You x, x1, x2 are not compile time constants, while s1, s2, y1, y2 are compile time constants

Inner classes may not declare static initializers (§8.7) or member interfaces, or a compile-time error occurs.

Inner classes may not declare static members, unless they are constant variables (§4.12.4), or a compile-time error occurs.




回答2:


You can just make the inner classes static.

static class A {

    static final Object x = new Object();
    static final String s = "s1";
    static final int y = 1;

    static class B {

        static final Object x1 = new Object();
        static final String s1 = "s1";
        static final int y1 = 1;

        static class C {

            static final Object x2 = new Object();
            static final String s2 = "s1";
            static final int y2 = 1;
        }
    }
}

Although obviously this will make some other things difficult.



来源:https://stackoverflow.com/questions/22297722/why-cant-i-declare-and-initialize-static-variable-in-inner-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!