immutable class should be final?

后端 未结 6 688
温柔的废话
温柔的废话 2020-11-29 09:15

It says in this article that:

Making a class final because it is immutable is a good reason to do so.

I\'m a bit puzzled by thi

6条回答
  •  渐次进展
    2020-11-29 10:00

    Because if the class is final you can't extend it and make it mutable.

    Even if you make the fields final, that only means you cannot reassign the reference, it does not mean you cannot change the object that is referred to.

    I don't see a lot of use in a design for an immutable class that also should be extended, so final helps keep the immutability intact.

提交回复
热议问题