Before converting the java class as Immuatable .
I will explain what is Mutable and Immutable
Mutable object - an object that is liable to change.
I will explain what is Mutable and Immutable
Mutable object - an object that is liable to change.
Immutable object - an object that is unchanging over time or unable to be changed.
For Ex:
IMMUTABLE :
String imm = "abc";
imm = "abc"+"d";
Here we are not adding the value to exist object ("abc"),
1)"d" will add to "abc",
2) will create new object "abcd"
3) the reference of "abc" will map to "abcd";
MUTABLE:
StringBuffer mut = new StringBuffer("abc");
mut.append("d");
Here the value of "mut" changing directly.
Guidelines to make a class immutable
1) Don’t provide “setter” methods — methods that modify fields or objects referred to by fields.
2) Make all fields final and private
3) Don’t allow subclasses to override methods
4) Special attention when having mutable instance variables
No comments:
Post a Comment