Why instance variable to be final?

前端 未结 4 1323
一整个雨季
一整个雨季 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:15

    The previous answers are wrong.

    To be immutable an object must declare all properties as final.

    There are certain guarantees that the Java Memory Model makes for final fields that protect them from returning incorrect default values when there are data races between threads.

    See example 17.5-2 in https://docs.oracle.com/javase/specs/jls/se7/html/jls-17.html#jls-17.5-110.

提交回复
热议问题