【问题标题】:Field can't be static?字段不能是静态的?
【发布时间】:2013-09-06 10:43:43
【问题描述】:

此代码有错误

public class DoIt {
    public static void main(String[] args) {
        final class Apple {
            public static String place = "doIt";
        }
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Constants.place);
            }
        });
        thread.start();
    }
}

错误-The field name cannot be declared static in a non-static inner type, unless initialized with a constant expression

【问题讨论】:

标签: java static nested-class


【解决方案1】:

问题是该字段是非final的:在非静态内部类的上下文中,只允许final字段是静态的:

final class Apple {
    // This should compile
    public static final String place = "doIt";
}

【讨论】:

  • 但是为什么会这样?因为我可以在这个方法中更改字段。
  • @JohnnyChen 您无法从其他方法访问该类,因为它是方法范围的。在main 之外无法说出Apple.place = "something-else";,因为从那里看不到Apple。如果您需要在 main 中使其可更改,请使用不同的机制使其工作。
【解决方案2】:

JLS 8.1.3

内部类不能声明静态成员,除非它们是常量 变量(第 4.12.4 节),或发生编译时错误。

final class Apple {
    public static final String place = "doIt"; // This is good
}

内部类是实例类。使用 static 成员的目的是直接调用它而无需实例化。因此,在内部类中允许静态成员没有多大意义。但是,您可以将它们声明为静态-

static final class Apple {
    public static String place = "doIt";
}

【讨论】:

    【解决方案3】:
     final class Apple { {  
         // you can't define non final field inside the final class
         // you have to use final with static
    
     }
    

    你可以使用

       public  final static String place = "doIt";
    

    【讨论】:

      【解决方案4】:

      根据Javatutorials

      一个本地类可以有静态成员,只要它们是常量变量。

      所以你必须将它声明为 final:

          public static void main(String[] args) {
          final class Apple {
              public static final String place = "doIt";
          }
          Thread thread = new Thread(new Runnable() {
              @Override
              public void run() {
                  System.out.println("");
              }
          });
          thread.start();
      }
      

      【讨论】:

        【解决方案5】:

        在我推理之前,错误术语如下

        术语: 嵌套类分为两类:静态和非静态。声明为静态的嵌套类简称为静态嵌套类。非静态嵌套类称为内部类(更具体地说是本地内部类)。

        现在在您的情况下,您有本地内部类。根据docsBecause an inner class is associated with an instance, it cannot define any static members itself.

        作为内部类实例的对象存在于外部类的实例中,并且在加载类时加载静态成员,而在您的情况下,您在加载类时无法访问 Apple 类以加载 place变量。

        如果本地类是常量变量,也可以有静态成员。

        所以你可以这样做public static final String place = "doIt";

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-02-12
          相关资源
          最近更新 更多