Saturday, 6 June 2015

Immutable Classes in Java

The best examples of immutable classes are String, Boolean, Byte, Short, Integer, Long, Float, Double etc. We can create immutable class by creating final class that have final data members.

Example:

public final class Student {
final int studentId;
public Student (int studentId){
this.studentId=studentId;
}
public int getStudentId (){
return studentId;
}
}
 The above class is immutable because:
  • The instance variable of the class is final.
  • we cannot create the subclass.
  • There is no setter methods i.e. we have no option to change the value of the instance variable.
Why immutable classes?
  1. Simplicity - each class is in one state only
  2. Thread Safe - because the state cannot be changed, no synchronization is required
  3. Writing in an immutable style can lead to more robust code.
Source:
http://www.javatpoint.com/how-to-create-immutable-class

Every Accomplishment starts with a decision to Try.....


No comments:

Post a Comment