错误:字段名称不能声明为static

时间:2013-08-30 06:07:59

标签: java multithreading static inner-classes

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

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

解决这个问题?

2 个答案:

答案 0 :(得分:8)

Java不允许您在函数本地内部类中定义非最终静态字段。只允许顶级类和静态嵌套类具有非最终静态字段。

如果您想在static课程中使用Constants字段,请将其设置为Application班级,如下所示:

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

答案 1 :(得分:6)

来自JLS section 8.1.3

  

内部类可能不会声明静态成员,除非它们是常量变量(第4.12.4节),否则会发生编译时错误。

如果你只是制作变量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();
    }
}

当然,如果您需要使用非常量值初始化它,这将无效。

说完所有这些,这是一个不寻常的设计,IMO。根据我的经验,很难看到一个命名的本地课程。你需要这是一个本地课吗?你想要实现什么目标?

相关问题