Why instance variable to be final?

前端 未结 4 1324
一整个雨季
一整个雨季 2021-01-12 15:57

I read this question about immutable objects and was left with a question regarding immutable objects and final field:

Why do we need instance variable in immutab

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-12 16:27

    There is no requirement as such to make the variable final. However, when it is true that you explicitly intend to never change the variable, it is often good practice to make it final, since that not only enforces the invariant against typos or other mistakes, but also declares the intent that it be immutable to, eg., other programmers or yourself.

    If the variable were public, then you would strictly need to make it final in order to ensure that interfacing code cannot change its value.

    Do note that the question you link is not directly related, however, as it discusses classes that are final, rather than variables. Making a class final means that it cannot be inherited from, not that it is immutable. There is certainly a case to be made for taking heed of the contents of that question and its answer when making immutable objects, however; but it is a separate question nonetheless.

提交回复
热议问题