Error: field name cannot be declared static

前端 未结 2 1341
余生分开走
余生分开走 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:17

    Java does not let you define non-final static fields inside function-local inner classes. Only top-level classes and static nested classes are allowed to have non-final static fields.

    If you want a static field in your Constants class, put it at the Application class level, like this:

    public class Application {
        static final class Constants {
            public static String name = "globe";
        }
        public static void main(String[] args) {
            Thread thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Constants.name);
                }
            });
            thread.start();
        }
    }
    
    0 讨论(0)
  • 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?

    0 讨论(0)
提交回复
热议问题