Why instance variable to be final?

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

    In immutable class you can not change the state of it's property/field. Generally it is done by not providing setter method to the client code of the class.

    And the combination of static final keyword is used to make a variable constant. A variable declared final can never be change it's value once it has been initialized.

    Since in immutable class you never need to change the property/field state, so it is better to make it final.

提交回复
热议问题