场不能是静态的吗?

2 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

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

das*_*ght 6

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

final class Apple {
    // This should compile
    public static final String place = "doIt";
}
Run Code Online (Sandbox Code Playgroud)