Difference between mutable and immutable object

JavaObject Oriented ProgrammingProgramming

In Java, state of the immutable object can’t be modified after it is created b ut definitely reference other objects. They are very useful in multithreading environment because multiple threads can’t change the state of the object so immutable objects are thread safe. Immutable objects are very helpful to avoid temporal coupling and always have failure atomicity.

On the other hand, Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

Sr. No.KeyMutable objectImmutable object
1
Basic
We can modify the state of a mutable object after it is created
We can't modify the state of the object after it is created.
2
 Thread safe
Mutable objects are not thread safe
Immutable objects are thread safe.
3
Final
Mutable class are not final
To create an immutable object, make the class final
4
Example
By default all class and it's object are mutable by nature.
String and all wrapper class  are the example of immutable classes

Example of Immutable Class

public final class ImmutableClass {
   private String laptop;
   public String getLaptop() {
      return laptop;
   }
   public ImmutableClass(String laptop) {
      super();
      this.laptop = laptop;
   }
}
public class Main {
   public static void main(String args[]) {
      ImmutableClass immutableClass = new ImmutableClass("Dell");
      System.out.println(immutableClass.getLaptop());
   }
}

Example of Muttable Class

public class MuttableClass {
   private String laptop;
   public String getLaptop() {
      return laptop;
   }
   public void setLaptop(String laptop) {
      this.laptop = laptop;
   }
   public MuttableClass(String laptop) {
      super();
      this.laptop = laptop;
   }
}
public class Main {
   public static void main(String args[]) {
      MuttableClass muttableClass = new MuttableClass("Dell");
      System.out.println(muttableClass.getLaptop());
      muttableClass.setLaptop("IBM");
      System.out.println(muttableClass.getLaptop());
   }
}
raja
Published on 09-Sep-2020 11:57:47
Advertisements