Larry Olson wrote:I know java allows final instance variables. But my question is what good is a final instance variable? If the value is final, it means all the objects of that class will have the same value for that instance variable. What purpose would it serve?
Why not replace it by a final static variable? Wouldn't it fit the requirement?
So why do we have a final instance variable in java?
Declaring instance as final informs compiler that some kind of optimalization on this instance is possible.
For example in this code:
if you declare 'b' as final, compiler knows that b will never change, so it can catch b in the register
and do not retrieve value of b from the memory on each loop cycle.
If b is not declared final, compiler knows that value of b could be changed at any time (for example inside someFunction)
and 'b' must be retrieved from the memory on each cycle.