How to Make
a Java Class Immutable
Making a class immutable Immutability must be familiar to every one when we talk about String & StringBuffer classes in java. Strings are considered immutable because the values contained in the reference variable cannot be changed. Whereas String Buffer is considered mutable because the value in a string buffer can be changed (i.e. mutable). However I always thought how to make our user defined classes as immutable though I am unaware as to why any one would need this. The reason perhaps might be clear once we have a look at the code. Now 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. Above do not provide any method where we modify the instance variables. Still done? No. How if some body creates a sub class from our up till now immutable class? Yes here lies the problem. The new subclass can contain methods, which over ride our base class (immutable class) methods. Here he can change the variable values. Hence make the methods in the class also final. Or a better approach. Make the immutable class itself final. Hence cannot make any sub classes, so no question of over ridding. The following code gives a way to make the class immutable. /*
// The immutable class which is made final
private final int count;
// Constructor where we can provide the constant value
// provide only methods which return the instance var
public int getCount()
public double getValue()
// class TestImmutable
System.out.println(obj1.getCount());
// there is no way to change the values of
count & value-
The possible use of immutable classes would be a class
containing a price list represented for a set of products.
Related:
Java Certification, Programming, JavaBean and Object Oriented Reference Books Return to : Java Programming Hints and Tips All the site contents are Copyright © www.erpgreat.com
and the content authors. All rights reserved.
|