Create Immutable Class in java

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.

final class MyImmutableClass {
    // instance var are made private & final to restrict the access
    private final int count;
    private final double value;

    // Constructor where we can provide the constant value
    public MyImmutableClass(int paramCount, double paramValue) {
        count = paramCount;
        value = paramValue;
    }

    // provide only methods which return the instance var
    //  not change the values

    public int getCount() {
        return count;
    }

    public double getValue() {
        return value;
    }
}


//class TestImmutable
public class TestImmutable {
    public static void main(String[] args) {
        MyImmutableClass obj1 = new MyImmutableClass(3, 5);
        System.out.println(obj1.getCount());
        System.out.println(obj1.getValue());
        // there is no way to change the values of count & value-
        // no method to call besides getXX, no subclassing, no public access to
        // var -> Immutable
    }
}

The possible use of immutable classes would be a class containing a price list represented for a set of products.

0 comments: