Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this private float field becoming zero?

Tags:

java

I have some peculiar behaviour which I'm struggling to explain to myself. A float field, called "textureScale", becomes zero.

That could be explained if some code was changing the value. However then I would expect to be able to cause a build failure, or at least a runtime exception, by setting it to a "private final float" - then whatever is changing the value will fail. But if I do that, the code doesn't fail at all - it works great!

Can anybody help me understand what is possible here - why might this float become zero unless I set it final? Is there a Java-ism which I am unfamiliar with here? Is the only explanation some obscurity in code elsewhere?

public class TexturedBox extends Box {
    // This field becomes 0.0?
    private float textureScale = 1.0f;

    public TexturedBox(Vector3f center, float x, float y, float z) {
        super(center, x, y, z);
    }

    @Override
    protected void duUpdateGeometryTextures() {
        FloatBuffer buf = BufferUtils.createFloatBuffer(24);

        buf.clear();

        // All the values in these puts are "zero" - since textureScale is now zero?
        buf.put(textureScale * 2f * xExtent); buf.put(0);
        buf.put(0); buf.put(0);
        buf.put(0); buf.put(textureScale * 2f * yExtent);
        buf.put(textureScale * 2f * xExtent); buf.put(textureScale * 2f * yExtent);
        // ... and more puts just like that ...

        buf.flip();

        setBuffer(Type.TexCoord, 2, buf);

        System.out.println(textureScale);
        // ^ This outputs zero
        // ... unless I set textureScale to final - then everything works?!
    }
}
like image 965
ledneb Avatar asked Dec 07 '22 05:12

ledneb


1 Answers

Set a breakpoint in the method. Is it called from the super constructor? If so, the field is not initialized at that point, because the super-constructor is called before the field initialization of the subclass.

If you declare the field final, the compiler may replace the field access with a constant expression, which will make it work

like image 59
Cephalopod Avatar answered Dec 28 '22 14:12

Cephalopod