Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Mutable objects and Immutable objects [duplicate]

Any one please give the diff between Mutable objects and Immutable objects with example.

like image 652
Rams Avatar asked Jan 11 '11 14:01

Rams


People also ask

What is the difference between immutable object and mutable object?

Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable.

Can immutable class be cloned?

Immutable objects are objects that don't change. You make them, then you can't change them. Instead, if you want to change an immutable object, you must clone it and change the clone while you are creating it. A Java immutable object must have all its fields be internal, private final fields.

What is difference between mutable and immutable files?

Mutable is a fancy way of saying that the internal state of the object is changed/mutated. So, the simplest definition is: An object whose internal state can be changed is mutable. On the other hand, immutable doesn't allow any change in the object once it has been created.

What is the difference between mutable and immutable objects in Java?

The mutable objects can be changed to any value or state without adding a new object. Whereas, the immutable objects can not be changed to its value or state once it is created. In the case of immutable objects, whenever we change the state of the object, a new object will be created.


1 Answers

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

A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).

class Mutable{   private int value;    public Mutable(int value) {      this.value = value;   }    //getter and setter for value }  class Immutable {   private final int value;    public Immutable(int value) {      this.value = value;   }    //only getter } 
like image 195
Ralph Avatar answered Oct 08 '22 10:10

Ralph