Immutable classes are those classes that cannot be modified after creation. If we want to modify immutable class then it will result in new immutable object.Immutable objects are very important in concurrency and they makes the programs efficient.
First we will see how to create an immutable object.As we know there are following step by which any object can be made as immutable:
1) Don't provide mutator methods for any field.
2) Make all the fields final and private
3) Don't allow subclasses by declaring the class final
4) Return deep cloned objects with copied content for all mutable fields in class
So we will apply these steps to create a immutable object.
public final class ImmutableClass{
private final String name;
private final String designation;
public ImmutableClass(String name,String designation){
this.name=name;
this.designation=designation;
}
public String getName(){
return name;
}
public String getDesignation(){
return designation;
}
}private final String name;
private final String designation;
public ImmutableClass(String name,String designation){
this.name=name;
this.designation=designation;
}
public String getName(){
return name;
}
public String getDesignation(){
return designation;
}
So above is an example of an immutable class.
But there can be a case when we have to include an mutable class(such as Date) within an immutable class, Then what can we do? We will make it as final member but it can be modified internally. So in this case the best practise is to return the copy of that object instead of original object. FOr this we can clone that object and return it.
For Example
public final ImmutableClassWithMutableObject{
private final Date date;
public ImmutableClassWithMutableObject(Date date){
this.date=new Date(date.getTime());
}
public Date getDate(){
return (Date)date.clone();
}
}
Advantages of immutable class:
1)They are thread safe so no need for synchronization
2)Immutable objects can be shared among threads without synchronization
3)Due to no synchronization performance of the application increases
4)They can be stored in cache and reused as Immutable objects Strings.
Disadvantage:
There is a huge disadvantage of creating garbage.Since immutable objects are use and throw so they create a huge garbage which reduces the performance of the application.
So above is all about immutable object.
0 comments:
Post a Comment