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)
Tyre Expiry and Tyre Safety
15 years ago
3 comments:
/* 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)
;)
Wow, we got one limitation now.
Post a Comment