1.

What do you mean by an immutable class? How can we make a class immutable?

Answer»

An immutable class doesn’t allow to change the state of its objects after creation. If we need to change that state of an object it will create a new object. One of the most popular examples of an immutable class is String. We need to TAKE care of several things to make a TYPE immutable. 

  1.  The class needs to be final. The reason for not allowing to extend it is that a subclass may GET access the sensitive fields or methods which may change the state of the object. 
  2.  The class should declare all its members as private. 
  3.  It should not offer APIs or public methods to change its state. For example setter methods. Even if it does, it should create a clone of its own, make the changes there and return the object. 
  4.  If any member of the class is mutable, we should declare it as final. 
  5. We should initialize the object through a constructor making a deep clone of the mutable objects passed as the constructor ARGUMENTS
  6. we should not expose the references of the mutable members OUTSIDE the class. If we need to do this, we need to clone the member properly and return it. This ensures even if the object is changed via its reference, it is not the same object. 


Discussion

No Comment Found