Any one please give the diff between Mutable objects and Immutable objects with example.
Objects whose value can change are said to be mutable. Objects whose value is unchangeable once they are created are called immutable.
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.
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.
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.
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With