Should I declare a java field 'final' when if it's not modified in code?

前端 未结 7 2060
终归单人心
终归单人心 2020-12-15 21:06

My question is mainly about performance. The compiler knows better that, for example, some variable is NOT modified after object instantiation. So, why bother with final?

7条回答
  •  清歌不尽
    2020-12-15 21:21

    I doubt it would matter from a performance point of view, but it still is probably a good idea in case you (but more likely some other new developer) later tries to modify that field in code. Having it marked as final will prevent you from even compiling that.

提交回复
热议问题