错误:字段名称不能声明为静态 [英] Error: field name cannot be declared static
本文介绍了错误:字段名称不能声明为静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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
解决方案?
推荐答案
Java不允许您在函数局部内部类内定义非最终静态字段.仅顶级类和静态嵌套类允许具有非最终静态字段.
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.
如果要在Constants
类中使用static
字段,请将其放在Application
类级别,如下所示:
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();
}
}
这篇关于错误:字段名称不能声明为静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文