为什么我在括号上出错?

时间:2013-11-09 21:12:09

标签: java lwjgl slick2d

代码:

public class EmptyTile extends TileEntity{ //error on this brace
    try{
        defaultTexture=TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png")); //defaultTexture is created in the class that this class extends
    }catch (IOException e) {
        e.printStackTrace();
    } //also an error on this brace
    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
    }
}

我也尝试将try / catch语句移动到EmptyTile构造函数,但它需要在调用超级构造函数之前初始化默认纹理,这显然是不允许的。

我也试过在这个类的父类中创建staticTexture变量static和regular。

3 个答案:

答案 0 :(得分:2)

您不能在类级别放置try/catch,只能在构造函数,方法或初始化程序块中。这是导致报告错误的原因。尝试在构造函数中移动代码,假设defaultTexture是属性:

public class EmptyTile extends TileEntity {

    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
        try {
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

但如果defaultTexture是静态属性,则使用静态初始化块:

public class EmptyTile extends TileEntity {

    static {
        try {
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
    }

}

答案 1 :(得分:0)

public class EmptyTile extends TileEntity{
    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
        try{
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png")); //defaultTexture is created in the class that this class extends
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请注意,如果TileEntity在构造函数中使用defaultTexture,则必须修改构造函数以允许它传入。

答案 2 :(得分:0)

如果您想在构造函数之外执行此操作,可以将其放在实例初始化程序块中:

public class EmptyTile extends TileEntity {

    // empty brace is instance initializer
    {
        try {
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
    }
}