Thursday, February 10, 2011

How to make class Immutable like String

1. make your class final, so that no other class can be inherited
2. Make sure that all variables are final and private.
3. No setter methods.
4. Provide a constructor which can take values to these variables.

Example:

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
}
}

1 comment:

  1. Can we assign values to final variables??
    private final int count;
    will fail as the value for count is not initialized.

    count = paramCount;
    will fail as count is final.

    ReplyDelete