What is Mutable and Imutable explain with examples? (java)
There are many concepts related to mutability and immutability.
Mutable : means changeable; Immutable : means unchangeable.
Some of the Immutable concepts:
Immutable classes : are also known as final classes. A class which you can't inherit (can't change the definition by extending it) is called as
immutable class. In some languages it is also called as shield classes. Eg: String class in java is immutable class, you can't inherit it.
use case: If you don't want any one to inherit your class and change the basic functionality of your class, then make it as immutable class.
This can be achieved by making your class as final class by using "final" keyword before your class.
Immutable variables (also know as final variables): also known as constants
Any variable that is declared as final, you can't modify its value.
eg: public static final double pi = 3.14; // we know that pi value will always remain same 3.14, no body can change its value. So we are declaring it as final , ie constant. So that no one can change its value.
Immutable methods (final methods): says, no body can modify or change my functionality.
Inherited classes (derived classes) can't override immutable methods.
use case: Framework generally gives lot of basic functionality where derived classes can't change. such kind of methods are made as final methods by using "final" keyword before that method name.
Immutable objects: (Note: don't misunderstand this with immutable variables)
an object for which we can't change the states(data) of it once it is set. If we can achieve this , then that object is called as immutable object.
For eg: String str = "hello";
In the above example hello is immutable, no body can change it. If you try to change it it will create a new string object.
String objects are examples of immutable objects.
Back To Top