Monday, December 24, 2007

Immutable Class: how to create

Mutable Class: State of the object can be changed.
Immutable Class: State of the object cannot be changed.

Steps to declare a class Immutable
1) Declare all the variables final. : State cant be chaaged.
2) Declare all the methods final. : To prevent subclasses from changing the class variables.
3) Pass the values for all the properties in constructor. : To initialize the variables by constructor.(One time setting).

4) At the most declare the class as final.(Not Necessary)

3 comments:

Vivek Athalye said...
This comment has been removed by the author.
Vivek Athalye said...

/* just removed the unnecessary java comments from the old post :| ... and added this one :D */

don't know how did i forget to add comment on this post in the past :D

anyway here it is...

what if i have an instance variable of some other class which is mutable? can u call this class as immutable?

eg:-

class Data
{
int id;

void incr()
{
id++;
}
}

final class DataContainer
{
final Data d = new Data();
}

class TestFinalVar
{
static DataContainer dc = new DataContainer();

public static void main(String args[])
{
System.out.println(dc.d.id);
dc.d.id++;
System.out.println(dc.d.id);
dc.d.incr();
dc.d.incr();
dc.d.id--;
System.out.println(dc.d.id);
}
}

/***********/
can you call DataContainer as immutable??

1. variable d is final.
2. no methods : so no final
3. instead of pass value in c'tor, i'm assigning new instance to "d".

4. i've even made the class final

but still i can change the value stored inside dc. (its the composition relationship in terms of UML)

;)

Tonnet said...

Wow, we got one limitation now.