Reputation: 11
i have a normal Java code, that just calculate a x-coordinate, but it is just 0;
private static final int startX = (Level.WIDTH / 2) - (Block.LENGTH * (Level.COLUMNS / 2));
At the time of calculating:
Level.WIDTH = 1000;
Block.LENGTH = 41;
Level.COLUMNS = 12;
Accord my calculation it must be 254, but its always 0. Did anybody know my error?
Upvotes: 0
Views: 182
Reputation: 394096
private static final int startX = (Level.WIDTH / 2) - (Block.LENGTH * (Level.COLUMNS / 2));
This variable is evaluated once when the class it belongs to is initialized. At the time that happens, the variables it depends on (Level.WIDTH
, Block.LENGTH
, Level.COLUMNS
) are probably still containing 0.
When declaring a final variable whose value depends on the value of other variables, those variables should also be final and be initialized before the variable that depends on them.
It's not mandatory, but your code won't make much sense otherwise, since changing, for example, the value of Level.COLUMNS
after startX
was initialized won't change the value of startX
, so it will seem to hold an inconsistent value.
Upvotes: 6