Error: field name cannot be declared static

前端 未结 2 1339
余生分开走
余生分开走 2021-01-19 00:01
public class Application {
    public static void main(String[] args) {
        final class Constants {
            public static String name = \"globe\";
        }
         


        
2条回答
  •  再見小時候
    2021-01-19 00:20

    From the JLS section 8.1.3:

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

    So you're fine if you just make the variable final:

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

    Of course this won't work if you need to initialize it with a non-constant value.

    Having said all of this, it's an unusual design, IMO. It's very rare to see a named local class at all, in my experience. Do you need this to be a local class? What are you trying to achieve?

提交回复
热议问题