Java – if I call a static method, does the constructor run

I have a class named tile with a static method public static buffered image grass(). The class also has a constructor public tile(), which sets a variable

So what I want to know is if I start from another class, tile If grass () calls the grass () method, will the constructor run?

I assume it's not because my grass () method returns null

This is my code:

import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

public class Tile {

    public static final int size = 50;

    private static BufferedImage mapSprites;

    public Tile(){
        try{
            Tile.setMapSprites(ImageIO.read(getClass().getResource("res/mas.png")));
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static BufferedImage grass(){
        return getMapSprites().getSubimage(0,10,10);;
    }

    private static BufferedImage getMapSprites() {
        return mapSprites;
    }

    private static void setMapSprites(BufferedImage mapSprites) {
        Tile.mapSprites = mapSprites;
    }
}

I can create a function to get mapsprite for each tile I return But I don't think it will be very effective Are there any other solutions?

(for reference only, I call it in the Map class).

public void render(){
    g.drawImage(Tile.grass(),null);
}

Solution

No, if you only call the static methods of the class, the constructor will not run There is no instance of a class associated with a static method call This is why mapsprites is empty

To populate mapsprites, you can move the code that initializes it out of the constructor and into the static initializer In this way, it will run the first time the class is referenced so that mapsprites can be properly initialized the first time the static method is called

static {
    try{
        Tile.setMapSprites(ImageIO.read(Tile.class.getResource("res/mas.png")));
    } catch (IOException e){
        e.printStackTrace();
    }
}

When using static initializers, care must be taken to avoid any exception propagation If so, it will be wrapped in exceptionininitializererror and thrown, which will be bad news for your program

You may also want to make the (now useless) constructor private to prevent instantiation of the class, because your class is now a utility class, everything is static, and instances of this class are now useless

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>