场不能是静态的吗?

时间:2013-09-06 10:43:44

标签: java static nested-class

此代码存在错误

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

3 个答案:

答案 0 :(得分:1)

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";
}

答案 1 :(得分:0)

根据Java tutorials

  

本地类可以拥有静态成员,前提是它们是常量变量。

所以你必须宣布最终:

    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();
}

答案 2 :(得分:0)

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

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

现在,在你的情况下,你有本地内部类。根据{{​​3}} Because an inner class is associated with an instance, it cannot define any static members itself.

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

此外,本地类可以拥有静态成员,前提是它们是常量变量。

所以你可以place

相关问题