Skip to main content

How to Make a Java 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.

/*
Code Developed By Ashish Agarwal
This code demonstrates the way to make a class immutable
*/

// The immutable class which is made final
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.
Otherwise also this represents a good design.

Comments

Popular posts from this blog

Asynchronous Vs. Synchronous Communications

Synchronous (One thread):   1 thread -> |<---A---->||<----B---------->||<------C----->| Synchronous (multi-threaded):   thread A -> |<---A---->| \ thread B ------------> ->|<----B---------->| \ thread C ----------------------------------> ->|<------C----->|

WebSphere MQ Interview Questions

What is MQ and what does it do? Ans. MQ stands for MESSAGE QUEUEING. WebSphere MQ allows application programs to use message queuing to participate in message-driven processing. Application programs can communicate across different platforms by using the appropriate message queuing software products. What is Message driven process? Ans . When messages arrive on a queue, they can automatically start an application using triggering. If necessary, the applications can be stopped when the message (or messages) have been processed. What are advantages of the MQ? Ans. 1. Integration. 2. Asynchrony 3. Assured Delivery 4. Scalability. How does it support the Integration? Ans. Because the MQ is independent of the Operating System you use i.e. it may be Windows, Solaris,AIX.It is independent of the protocol (i.e. TCP/IP, LU6.2, SNA, NetBIOS, UDP).It is not required that both the sender and receiver should be running on the same platform What is Asynchrony? Ans. With messag...

Advantages & Disadvantages of Synchronous / Asynchronous Communications?

  Asynchronous Communication Advantages: Requests need not be targeted to specific server. Service need not be available when request is made. No blocking, so resources could be freed.  Could use connectionless protocol Disadvantages: Response times are unpredictable. Error handling usually more complex.  Usually requires connection-oriented protocol.  Harder to design apps Synchronous Communication Advantages: Easy to program Outcome is known immediately  Error recovery easier (usually)  Better real-time response (usually) Disadvantages: Service must be up and ready. Requestor blocks, held resources are “tied up”.  Usually requires connection-oriented protocol