point of having an instance variable as final?

前端 未结 6 418
醉梦人生
醉梦人生 2021-02-01 23:25

what is the point of having an instance variable as final?

isn´t it better to have that variable set as a static final variable then?

cause if it can\'t be chang

6条回答
  •  不思量自难忘°
    2021-02-02 00:07

    Two reasons:

    1) From the class design view, it allows a programmer to rely on the fact that the field will not change since instantiation - so called "immutable object" (where applied to class members, not the object's reference). Java tutorial says:

    Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

    Immutable objects are a cornerstone of various programming styles, e.g. pure functional programming.

    2) The second reasons is JVM optimizations. If all fields are final, then JVM knows the object's state can't be changed, and thus it can make many optimizations, e.g. ommiting thread safety checks etc.

提交回复
热议问题