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();
}
}
编译错误:字段名称不能在非静态内部类型中声明为静态,除非用常量表达式初始化
解决这个问题?
最佳答案
Java 不允许您在局部函数内部类中定义非最终静态字段。仅顶级类和静态嵌套类允许具有非最终静态字段。
如果你想在你的Constants
类中有一个static
字段,把它放在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();
}
}
关于java - 错误 : field name cannot be declared static,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18526099/