Error: field name cannot be declared static

五迷三道 提交于 2019-12-01 18:27:15

问题


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

Compilation Error: The field name cannot be declared static in a non-static inner type, unless initialized with a constant expression

Solution to this?


回答1:


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



回答2:


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?



来源:https://stackoverflow.com/questions/18526099/error-field-name-cannot-be-declared-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!