MY mENU


Thursday 9 February 2012

Immutable class in Java

It's Possible to make a class as immutable.



In order to make a Class Immutable we must restrict changing the state of the Class object by any means. This in turn means avoiding an assignment to a variable. We can achieve this through a final modifier. To further restrict the access we can use a private access modifier. Do not provide any method where we modify the instance variables.

Somebody can create the SubClass, that can contain methods, which over ride our base class (Immutable Class) methods. Here he can change the variable values.
- So to avoid that make the Methods in the Class also final. Or a better approach is to make the Immutable Class itself final. Hence cannot make any sub classes, so no question of over ridding.


public class final ClassName
{
---
--- all properties must be final and private
private final int i =10;

---
--- all behaviours must be final
}



An Object is considered immutable if its state cannot change after it is constructed.

Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state.

No comments:

Post a Comment