Must all properties of an immutable object be final?

how to change immutable object in java
why immutable class is final
immutable objects in java

Must immutable objects have all properties be final?

According to me not. But I don't know, whether I am right.

Must all properties of an immutable object be final?, The main difference between an immutable object (all properties final) and an effectively immutable object (properties aren't final but can't be  Is it a must to declare all variables final. No, it is not mandatory to have all properties final to create an immutable object. In immutable objects you should not allow users to modify the variables of the class. You can do this just by making variables private and not providing setter methods to modify them. Example

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.

How to create an immutable class in Java without using final , MyBigDecimal extends java. math. BigDecimal { public MyBigDecimal(double val) { super(val); } private int count = 0; // override intValue which changes the state of this instance @Override public int intValue() { return count++; } // rinse and repeat for the rest of the BigDecimal methods } Must immutable objects have all properties be final? According to me not. But I don't know, whether I am right.

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.

final vs Immutability in Java, means that the object's actual value can't be changed, but you can change its reference to another one. No. If those properties/attributes are private and there’s no getter for the same, i.e. if those aren’t exposed to outer world, they need not be final. The idea of immutability is to maintain the state of the object, that is created during the object creation. If you are satisfying this condition, you’re well and good.

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

Why String is Immutable or Final in Java, was modified after insertion, potentially losing the value object in the map. Hello Friends,In this video we will discuss on one of very important interview question in java that is Do all properties of an Immutable Object need to be final? Follow me on Social network:

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;
}

Immutable Objects in Java, Do all properties of an Immutable Object need to be final in java?||[All about Immutability in Duration: 11:18 Posted: May 16, 2019 Threads can concurrently access immutable objects without bothering with possible race conditions. Immutable objects are always thread-safe. The Java Memory Model offers a special guarantee of initialization safety. In other words, a reference to an immutable object can be freely shared between as many threads as you want without synchronization.

Do all properties of an Immutable Object need to be final , must be do The main difference between an immutable object (all properties final) and an effectively immutable object (properties aren't final but can't be  Whenever they say "immutable object", they are always talking about thread safe immutable objects. The idiomatic way to implement immutable objects is to use final fields; final semantics was specifically upgraded to support immutable objects.

Do all properties of an immutable object need to be final in , final modifier is applicable for variable but not for objects, Whereas immutability applicable for an object but not for variables. By declaring a reference variable as​  Moreover, I think that all classes should be immutable in a perfect object-oriented world. Unfortunately, sometimes, it is technically not possible due to limitations in JVM. Nevertheless, we should always aim for the best. This is an incomplete list of arguments in favor of immutability: immutable objects are simpler to construct, test, and use

Does making all fields Final makes the class Immutable in Java?, If you must, then consider returning a copy or clone of the mutable object. If you are returning a collection, you could wrap it as an unmodifiable  A Java immutable object must have all its fields be internal, private final fields. It must not implement any setters. It needs a constructor that takes a value for every single field. Immutable objects come in handy in multi-threaded environments and in streams.

Comments
  • Well final just makes so that you can't reassign the field.. the object referenced by a final field could be mutable
  • 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?
  • how will an object with non final private fields (initialized on object construction) ever be thread unsafe ?
  • If all their fields are final they can still be safely published but it is not enough to make them thead safe.
  • 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.
  • @NimChimpsky I have clarified how an effectively immutable object could cause thread safety issues.
  • in the first case someone can extend the class and change subclass's state and assign to parent class reference thus changing state.
  • 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.
  • 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 reference
  • 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 help