简体   繁体   中英

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:

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. How would I go about declaring a public static final variable?

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 . In your example, STONE is a local variable in the scope of the loadTextures() method.

You could define it as a public static final data member, and initialize in a static block:

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. You need to move it outside the method and declare the variable at class level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM