【问题标题】:Why we have to declare static variable as final in inner class? [duplicate]为什么我们必须在内部类中将静态变量声明为 final? [复制]
【发布时间】:2016-07-01 13:16:20
【问题描述】:

我的代码是这样的:

    public class BookStore {
             class Enumerator1 {   
                 static int b = 0;//requires final
             }

         public String searchBook(final String criteria) {
             class Enumerator2 {   
                 static int b = 0;//requires final
             }
             return "";
         }
    }

这里我不能将 b 声明为 static 它需要是常量。我不明白为什么?

【问题讨论】:

标签: java


【解决方案1】:

因为类本身实际上不是静态的,所以非最终静态声明意味着每个父实例有一个实例,这是不可能的。 “final”基本上是一个常数,所以不会造成任何问题。

如果你也声明内部类为静态,你可以在里面有静态变量:

public class BookStore {
         static class Enumerator1 {   
             static int b = 0;// works
         }

     public String searchBook(final String criteria) {
         class Enumerator2 {   
             final static int b = 0; // still necessary as the class can't be static here
         }
         return "";
     }
}

【讨论】:

    【解决方案2】:

    内部类的所有static 声明必须在父类中。 static final 被视为常量,因此实际上不占用真正的静态空间,因此您可以在内部类中使用它们。

    【讨论】:

      【解决方案3】:

      JLS 声明“内部类不能声明静态成员,除非它们是常量变量”。此禁令背后的原因是依赖于对象的类中的类变量极有可能造成混淆。

      考虑一个简单的例子:

      class Parent {
          public class Child {
              static int count = 1; // Let's pretend that it is possible
              public void increment() {
                  count++;
              }
              public void show() {
                  System.out.println(count);
              }
          }
          public Child generateChild() {
              return new Child();
          }
      }
      

      现在假设我们这样做:

      Parent p1 = new Parent();
      Parent.Child c1 = p1.generateChild();
      Parent p2 = new Parent();
      Parent.Child c2 = p2.generateChild();
      c2.show();
      c1.increment();
      c2.show();
      

      父 1 的子级的增量会导致不同父级的子级发生变化,即使 Child 类附加到其 Parent 类,因此不同父级的子级应该具有独立的上下文。

      Java 语言设计者推断,如果您确实想要这种行为,那么将静态变量放在父类中是没有问题的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-04-13
        • 1970-01-01
        • 2013-05-06
        • 2011-10-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多