简体   繁体   中英

How to create uninitialised static final variables in Java

The code below produces the compiler error Variable HEIGHT might not have been initialized (same goes for WIDTH ).

How can I declare an uninitialized static final variable like what I'm trying to do below?

public static final int HEIGHT, WIDTH;
static{
    try {
        currentImage = new Image("res/images/asteroid_blue.png");
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
    }catch (SlickException e){
        e.printStackTrace();
    }
}
  static {
    Image currentImage = null;
    try {
      currentImage = new Image("res/images/asteroid_blue.png");
    } catch (Exception e) {
      // catch exception - do other stuff
    } finally {
      if (currentImage != null) {
        WIDTH = currentImage.getWidth();
        HEIGHT = currentImage.getHeight();
      } else {
        // initialise default values
        WIDTH = 0;
        HEIGHT = 0;
      }
    }
  }

Whatever happens (try/catch), you have to assign values to the static variables - therefor, finally should be used.

The right way would be to set the values to null (in case its an object), but since it's final you'll have to do this roundabout:

public static final int HEIGHT, WIDTH;
static{
    int w = 0, h = 0;
    try {
        currentImage = new Image("res/images/asteroid_blue.png");
        w = currentImage.getWidth();
        h = currentImage.getHeight();
    }catch (SlickException e){
        e.printStackTrace();
    }

    WIDTH = w;
    HEIGHT = h;  
}

You can do this but you need to exit the static block by throwing an exception

  public static final int HEIGHT, WIDTH;
  static{
   try {
      currentImage = new Image("res/images/asteroid_blue.png");
      WIDTH = currentImage.getWidth();
      HEIGHT = currentImage.getHeight();
  }catch (SlickException e){
      e.printStackTrace();
     throw new RuntimeException("Could not init class.", e);    
 }

}

You can't. final variables can only be assigned values during initialization, hence why you're receiving compiler error (the variables will stay null). It's used to ensure consistency.

You can either drop the final keyword or make HEIGHT and WIDTH local variables.

currentImage = new Image("res/images/asteroid_blue.png");
final int width= currentImage.getWidth();
final int height = currentImage.getHeight();

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