Must all properties of an immutable object be final?
Asked Answered
A

8

51

Must immutable objects have all properties be final?

I would say they don't. But I don't know whether I am right or not.

Anandrous answered 17/4, 2013 at 13:13 Comment(1)
Well final just makes so that you can't reassign the field.. the object referenced by a final field could be mutableEbonee
O
58

The main difference between an immutable object (all properties final) and an effectively immutable object (properties aren't final but can't be changed) is safe publication.

You can safely publish an immutable object in a multi threaded context without having to worry about adding synchronization, thanks to the guarantees provided by the Java Memory Model for final fields:

final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.

As a side note, it also enables to enforce immutability (if you try to mutate those fields in a future version of your class because you have forgotten it should be immutable, it won't compile).


Clarifications

  • Making all the fields of an object final does not make it immutable - you also need to make sure that (i) its state can't change (for example, if the object contains a final List, no mutating operations (add, remove...) must be done after construction) and (ii) you don't let this escape during construction
  • An effectively immutable object is thread safe once it has been safely published
  • Example of unsafe publication:

    class EffectivelyImmutable {
        static EffectivelyImmutable unsafe;
        private int i;
        public EffectivelyImmutable (int i) { this.i = i; }
        public int get() { return i; }
    }
    
    // in some thread
    EffectivelyImmutable.unsafe = new EffectivelyImmutable(1);
    
    //in some other thread
    if (EffectivelyImmutable.unsafe != null
        && EffectivelyImmutable.unsafe.get() != 1)
        System.out.println("What???");
    

    This program could in theory print What???. If i were final, that would not be a legal outcome.

Orthopedics answered 17/4, 2013 at 13:15 Comment(8)
while I do agree with u, what about an object that has an array field that is final? The reference is immutable, but the values are not. Same thing about ImmutableList of StringBuilders for example. Are these objects considered thread-safe?Lickerish
how will an object with non final private fields (initialized on object construction) ever be thread unsafe ?Dobsonfly
If all their fields are final they can still be safely published but it is not enough to make them thead safe.Orthopedics
In what situation would they be thread unsafe ? Nothing can change after object creation ... so I don't undestand how they would ever be unsafe.Dobsonfly
@Dobsonfly I have clarified how an effectively immutable object could cause thread safety issues.Orthopedics
If an immutable class uses an array to encapsulate a sequence of values, how should it ensure that writes to array elements will be visible before the class gets exposed to outside code?Beka
I don't really understand the last example you give. Could you elaborate that part? I understand the first statement but not the second one. How would final make it illegal?Evident
@AdrienBrunelat in the example, there is a data race and there is no guarantee that a non null object will be fully constructed (i.e. a field could still be uninitialised). If the fields are final, the JLS guarantees that they will be initialised even if the object is accessed via a data race (cf. the quote in my answer).Orthopedics
G
14

You can easily guarantee immutability by encapsulation alone, so it's not necessary:

// This is trivially immutable.
public class Foo {
    private String bar;
    public Foo(String bar) {
        this.bar = bar;
    }
    public String getBar() {
        return bar;
    }
}

However, you also must guarantee it by encapsulation in some cases, so it's not sufficient:

public class Womble {
    private final List<String> cabbages;
    public Womble(List<String> cabbages) {
        this.cabbages = cabbages;
    }
    public List<String> getCabbages() {
        return cabbages;
    }
}
// ...
Womble w = new Womble(...);
// This might count as mutation in your design. (Or it might not.)
w.getCabbages().add("cabbage"); 

It's not a bad idea to do so to catch some trivial errors, and to demonstrate your intent clearly, but "all fields are final" and "the class is immutable" are not equivalent statements.

Garrick answered 17/4, 2013 at 13:19 Comment(3)
in the first case someone can extend the class and change subclass's state and assign to parent class reference thus changing state.Ryle
Yes, but it depends on the context if you think the rogue subclasser is a likely scenario. Declaring a class as final or adhering to the open-closed principle in code review would address that. That said the child class cannot change the value of bar in any case legitimately, so Foo as declared is immutable, and I have a hunch will appear so to all clients of such an object through the interface exposed by Foo.Garrick
Actually this might even adhere to the OCP. It’s not great design but in effect it’s as if you bundled two independent objects, one mutable and one not, under one referenceGarrick
D
6

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.

Docilu answered 17/4, 2013 at 13:15 Comment(1)
i have a question: how we can achieve functionality like string class for ex. in case of string class String firstname = new String("amar"); String name ="amar"; so both firstname and name will point to the same memory location on stack please helpExtent
I
6

Simply declaring an object as final does not make it inherently immutable. Take for example this class:

import java.util.Date;

/**
* Planet is an immutable class, since there is no way to change
* its state after construction.
*/
public final class Planet {

  public Planet (double aMass, String aName, Date aDateOfDiscovery) {
     fMass = aMass;
     fName = aName;
     //make a private copy of aDateOfDiscovery
     //this is the only way to keep the fDateOfDiscovery
     //field private, and shields this class from any changes that 
     //the caller may make to the original aDateOfDiscovery object
     fDateOfDiscovery = new Date(aDateOfDiscovery.getTime());
  }

  /**
  * Returns a primitive value.
  *
  * The caller can do whatever they want with the return value, without 
  * affecting the internals of this class. Why? Because this is a primitive 
  * value. The caller sees its "own" double that simply has the
  * same value as fMass.
  */
  public double getMass() {
    return fMass;
  }

  /**
  * Returns an immutable object.
  *
  * The caller gets a direct reference to the internal field. But this is not 
  * dangerous, since String is immutable and cannot be changed.
  */
  public String getName() {
    return fName;
  }

//  /**
//  * Returns a mutable object - likely bad style.
//  *
//  * The caller gets a direct reference to the internal field. This is usually dangerous, 
//  * since the Date object state can be changed both by this class and its caller.
//  * That is, this class is no longer in complete control of fDate.
//  */
//  public Date getDateOfDiscovery() {
//    return fDateOfDiscovery;
//  }

  /**
  * Returns a mutable object - good style.
  * 
  * Returns a defensive copy of the field.
  * The caller of this method can do anything they want with the
  * returned Date object, without affecting the internals of this
  * class in any way. Why? Because they do not have a reference to 
  * fDate. Rather, they are playing with a second Date that initially has the 
  * same data as fDate.
  */
  public Date getDateOfDiscovery() {
    return new Date(fDateOfDiscovery.getTime());
  }

  // PRIVATE //

  /**
  * Final primitive data is always immutable.
  */
  private final double fMass;

  /**
  * An immutable object field. (String objects never change state.)
  */
  private final String fName;

  /**
  * A mutable object field. In this case, the state of this mutable field
  * is to be changed only by this class. (In other cases, it makes perfect
  * sense to allow the state of a field to be changed outside the native
  * class; this is the case when a field acts as a "pointer" to an object
  * created elsewhere.)
  */
  private final Date fDateOfDiscovery;
}
Instillation answered 17/4, 2013 at 13:19 Comment(0)
L
5

Immutable objects MUST not be modified in any way after their creation. final of course helps to achieve that. You guarantee that they will not ever be changed. BUT what if you have an array inside your object that is final? Of course the reference is not changable, but the elements are. Look here at almost the same question I gave also:

Link

Lickerish answered 17/4, 2013 at 13:16 Comment(0)
K
2

No.

For example, see the implementation of java.lang.String. Strings are immutable in Java, but the field hash is not final (it is lazily computed the first time hashCode is called and then cached). But this works because hash can take on only one nondefault value that is the same every time it is computed.

Koosis answered 24/4, 2013 at 10:54 Comment(0)
N
2

String class is Immutable but property hash is not final

Well it is possible but with some rules/restrictions and that is access to mutable properties/fields must provide same result every time we access it.

In String class hashcode actually calculated on the final array of characters which is not going to change if String has constructed. Therefore immutable class can contain mutable fields/properties but it has to make sure that access to field/property will produce the same result every time it is accessed.

To answer your question it is not mandatory to have all the fields final in a immutable class.

For further reading visit here [blog] : http://javaunturnedtopics.blogspot.in/2016/07/string-is-immutable-and-property-hash.html

Nutbrown answered 22/7, 2016 at 11:29 Comment(0)
S
0

Not necessary, you can achieve same functionality by making member as non-final but private and not modifying them except in constructor. Don't provide setter method for them and if it is a mutable object, then don't ever leak any reference for that member.

Remember making a reference variable final, only ensures that it will not be reassigned a different value, but you can still change individual properties of an object, pointed by that reference variable. This is one of the key points.

Silvertongued answered 24/1, 2019 at 22:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.