[英]Can't public static on a final
I am sure there's a super simple explanation and it'll make me feel stupid, but I just can't figure it out. 我敢肯定有一个超级简单的解释,这会让我感到愚蠢,但我只是想不通。 Pastebin , line 18: Pastebin ,第18行:
public static boolean loadTextures() {
try {
final Texture STONE = loadPNG("main\\textures\\stone.png"); // This line here I can't do public static final...
} catch (IOException e) {
return false;
}
return true;
}
I would like STONE
to be public static final
, but eclipse says only final
is a legal modifier. 我希望STONE
成为public static final
,但是eclipse说只有final
是合法的修饰符。 How would I go about declaring a public static final
variable? 我将如何声明public static final
变量?
You can't declare a static variable inside a method, since a method has only local variables. 您不能在方法内部声明静态变量,因为方法仅具有局部变量。
Move it outside your method. 将其移到您的方法之外。
Change this : 改变这个:
public static boolean loadTextures() {
try {
final Texture STONE = loadPNG("main\\textures\\stone.png"); // This line here I can't do public static
to this : 对此:
public static final Texture STONE = loadPNG("main\\textures\\stone.png");
public static boolean loadTextures() {
try {
public
and static
are modifiers that can be applied to data members . public
和static
是可以应用于数据成员的修饰符。 In your example, STONE
is a local variable in the scope of the loadTextures()
method. 在您的示例中, STONE
是loadTextures()
方法范围内的局部变量。
You could define it as a public static final
data member, and initialize in a static
block: 您可以将其定义为public static final
数据成员,然后在static
块中进行初始化:
public static final Texture STONE;
static {
try {
STONE = loadPNG("main\\textures\\stone.png");
} catch (IOException e) {
// some error handling...
}
}
The biggest problem here, as can be seen is the exception handling. 可以看出,这里最大的问题是异常处理。 Since this is invoked when the class is loaded by the classloader, there's no real good way to handle potential exceptions there. 由于当类加载器加载类时会调用此方法,因此没有真正好的方法在那里处理潜在的异常。
final
is the only valid modifier allowed for a local variable. final
是局部变量唯一允许的有效修饰符。 You need to move it outside the method and declare the variable at class level. 您需要将其移到方法之外,并在类级别声明变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.