Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to make class immutable ?

 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,

I have one doubt and is that "How we can make Immutable class ?"

I mean we say that string is immutable class because it creates the new object and keep old one as it is .In the same way how can we make our own class as Immutable or how immutability can be achieved.

Will it be the case that our class be immutable after declaring it as final ?

Again one question is that "Are all wrapper classes are immutable ? "

Thank you all in advance.

Regards,
Chetan
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Likes 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chetan Dorle wrote:Dear All,

I have one doubt and is that "How we can make Immutable class ?"


By not having any way to change its state after creation.

I mean we say that string is immutable class because it creates the new object and keep old one as it is .


No, we say that String is immutable because it doesn't provide any means to change its state after creations. The fact that we have to create a new String object if we want a String with a different state is a +result+ of String's immutability.

Will it be the case that our class be immutable after declaring it as final ?


No. Your class being final simply means that nothing can extend it. It has nothing to do with whether an instance of that class can change its state after creation. There is no keyword or language level construct to indicate immutability (though I wish there was).

Again one question is that "Are all wrapper classes are immutable ? "


You can discover this for yourself by look at all their javadocs. If they say that the class is immutable, or if the class doesn't provide any means to change its state, then it's immutable.
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To make a class final, you need to make sure it's internal state can not change, or at least not in such a way that will be visible to the outside world.

This means your class can only have pure functions. None of the methods may change important fields. If the constructor accepts a mutable class as an argument, you should make a defensive copy of the argument before assigning it to a field. When you want to return a mutable field, you should instead make a copy of the object and return that copy.

All your methods should be final to prevent a subclass from turning them into versions that break these properties. The easiest way to do this is to just make the class itself final.
 
Jeff Verdegan
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:To make a class final, you need to make sure it's internal state can not change,


Presumably you meant, "To make a class immutable..."
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Errr.... yes ^^'
 
AbdulRab Khan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
An immutable object is an object whose state cannot be modified after it is created.

Following is the template for creating immutable objects:

1) Make all fields private
2) Don't provide mutators
3) Ensure that methods can't be overridden by either making the class final (Strong Immutability) or making your methods final (Weak Immutability)
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are forgetting a very important step. You need to perform defensive copying in the constructor and any accessors, if they respectively accept and return mutable types.
 
Winston Gutkowski
Bartender
Pie
Posts: 10109
56
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chetan Dorle wrote:Will it be the case that our class be immutable after declaring it as final ?

No, but it's an important part of it. While it is possible to create a non-final immutable class, it is not possible to create an immutable class that is publically extendable (or perhaps nonsensical is a better term), because then anyone could add a mutable portion to it. So the easiest thing generally is to make it final. However, as others have said, that's not the end of it...

Winston
 
AbdulRab Khan
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:You are forgetting a very important step. You need to perform defensive copying in the constructor and any accessors, if they respectively accept and return mutable types.


Thanks Stephan van Hulst, I was'nt aware of this step
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To illustrate this problem:

In the first snippet, the class is not really immutable, because you can change its state by changing the Mutable object you pass to the constructor, or by changing it after you retrieve it with the accessor method.
The second snippet demonstrates an Immutable variant. It uses a copy constructor in the Mutable class to make defensive copies of it before it stores or returns the object.
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can also solve the problem for accessor methods by returning read-only views of the mutable object in question. For example, if you have a class which contains a list of objects, and you want to return the list from a method, you can return a read-only view of it by returning Collections.unmodifiableList(myList);
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, even that won't make the class immutable unless the elements of the List are immutable too. If not, you can modify individual elements of the unmodifiable List; unmodifiable only means the List cannot have elements added, removed or replaced, it doesn't say anything about the content of the elements themselves.
 
Stephan van Hulst
Bartender
Pie
Posts: 5406
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Err yes. My bad.
 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all , Guys ....for the examples and your replies.

here is one link i found http://download.oracle.com/javase/tutorial/essential/concurrency/imstrat.html
 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Key Notes:-

Declare class as final (strong immutability)
No parameterized constructor (only default is allowed)
Only allow get() methods are allowed
Member variables of class as private and final.
 
Rob Spoor
Sheriff
Pie
Posts: 20495
54
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santosh Kumar Nayak wrote:No parameterized constructor (only default is allowed)

How are you going to give your objects any state? Immutable classes usually have constructors that do have parameters. You just have to make sure that the arguments to the constructor are either immutable as well, or are copied defensively.
 
Ulf Lindqvist
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chetan Dorle wrote:
There is no keyword or language level construct to indicate immutability (though I wish there was).


Well you can always use C++ which has the const keyword.

Still the keyword approach has its limits and that's because immutability comes in two flavours, formal and by design, and that's really an issue. To resolve it C++ has had to introduce a counter measure to const called mutable.

So with the C++ example in mind and further discouraged by the general threat that "if you suggest a language change you must donate a kidney" I think Java should stay as it is.

 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can Immutable class have a reference to a mutable class ?
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but you have to take defensive copies of any mutable fields if they enter or leave the class.
 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are two classes : Person and Employee.

Now object of Person class has been passed to Employee class as argument.

Now my question is how should we make sure that Object of Person class remains unaltered (class Person is mutuable).

There are chances that within class Employee the object of Person class can be altered.


 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The Person object cannot ensure constancy of its state in those circumstances.
The Employee object must take a defensive copy of the Person object or its fields to establish immutability. That will usually be done in such a manner as not to alter the state of the Person object.
 
Winston Gutkowski
Bartender
Pie
Posts: 10109
56
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Santosh Kumar Nayak wrote:There are chances that within class Employee the object of Person class can be altered.

In which case, I wonder on what basis you could consider an Employee to be "immutable"?

As previously explained, whatever way you choose to do it, it is going to cause an Employee to hold a snapshot of a Person; and in that case, I'd say that the two classes are unrelated, simply because of their differing requirements for mutability.

Winston
 
Santosh Kumar Nayak
Ranch Hand
Posts: 143
Eclipse IDE IntelliJ IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you elaborate as what do you mean by defensive copy of the object.
 
Campbell Ritchie
Sheriff
Posts: 48424
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You create another object with the same details in its fields.. It may be mutable, but you keep it hidden as a private field and its state never changes. If any of those fields are mutable, they would need to be copied too.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic