This is forcing the field to be final in order to make the class immutable
I doubt if I should make the class immutable.
As per the java docs.
- I made the final grade (no one can renew) Field
- is closed.
- there is no setter function.
- If the fields are mutable, then submit a cloned copy of the field.
I doubt its a must to create a field of my class like final
?
source to share
While many say that it is not necessary to mark fields as final, I would say in at least one case that I can think of you needing to mark fields as final, and that is in case you want to make yours immutable thread safe class.
According to Java Memory Model: -
An object is considered fully initialized when its constructor ends. A thread that can only see a reference to an object after that object has been fully initialized is guaranteed to see correctly initialized values for the final fields of that object.
So, if you have an immutable class with instance variables that you initialize in the constructor as non-final variables, then there is no guarantee of thread safety, as writes to odd variables may not be available to other threads, although the constructor has to completely execute (Note recreating this is very difficult as it can happen in a highly competitive application)
source to share
Immutability = does not change . So creating final properties is a good idea. If not all properties of an object are protected from change, I would not say that the object is immutable.
BUT an object is also immutable if it does not provide any settings for its private properties.
The object immutable
will never change, but whatever it refers to can change.
Deep immutability
much stronger: neither the base object nor any object you can navigate from will change.
source to share