immutable class should be final?

后端 未结 6 610
温柔的废话
温柔的废话 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:05

    So, why is immutability a good reason for making a class final?

    As stated in oracle docs there are basically 4 steps to make a class immutable.

    So one of the point states that

    to make a class Immutable class should be marked as either final or have private constructor

    Below are the 4 steps to make a class immutable (straight from the oracle docs)

    1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.

    2. Make all fields final and private.

    3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.

    4. If the instance fields include references to mutable objects, don't allow those objects to be changed:

      • Don't provide methods that modify the mutable objects.
      • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

提交回复
热议问题