简体   繁体   中英

is it compulsion to make field as final to make class immutable

I have doubt a doubt regarding making an immutable class.

As per the java docs.

  1. I made the class final( no one can extend)
  2. field are private.
  3. no setter function.
  4. If fields are mutable then send a cloned copy of the field.

My doubt is that its compulsory to make a field of my class as final ?

If there are no setter methods (and presumably no other methods to affect the fields' values) and the fields themselves are private , marking them as final is somewhat redundant. Having said that - its a good defensive practice which many projects' standards follow.

Although as many say its not mandatory to mark the fields as final I would say atleast in one case that I can think of you need to mark the fields as final and that is in the case if you want to make your immutable class thread safe.

According to Java memory model:-

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

JLS final thread safety

So if you have an immutable class with instance variables which you initialize in constructor as non final variables then there is no guarantee of thread safety as the writes to the non final variables may not be visible to other threads even though the constructor has fully run ( Note recreating this is very difficult as this may occur in a highly concurrent application)

Immutable = not changeable . So making properties final is a good idea. If not all properties of an object are protected from being changed I wouldn't say the object is immutable.

BUT an object is also immutable if it doesn't provide any setters for it's private properties.

An immutable object will never change, but anything that it refers to might change. Deep immutability is much stronger: neither the base object nor any object you can navigate to from it will change.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM