Are all final class immutable?

前端 未结 8 2306
一生所求
一生所求 2021-02-19 09:34

Are all final classes in Java immutable. String and Integer both are final classes and both are immutable i beleive.

8条回答
  •  甜味超标
    2021-02-19 10:14

    As has been said by the others before final does not make a class imuutable in Java though it plays a part in the immutability strategy. To obtain immutability you should follow the general guidlines:

    • ensure the class cannot be overridden - make the class final, or use static factories and keep constructors private
    • make fields private and final
    • force callers to construct an object completely in a single step, instead of using a no-argument constructor combined with subsequent calls to setXXX methods (that is, avoid the Java Beans convention)
    • do not provide any methods which can change the state of the object in any way - not just setXXX methods, but any method which can change state
    • if the class has any mutable object fields, then they must be defensively copied when passed between the class and its caller

提交回复
热议问题