aspose file tools*
The moose likes Java in General and the fly likes How to make class immutable ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to make class immutable ?" Watch "How to make class immutable ?" New topic
Author

How to make class immutable ?

Karn Kumar
Ranch Hand

Joined: Aug 06, 2009
Posts: 146

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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Sep 20, 2010
Posts: 3647
    
  16

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

Joined: Jan 03, 2004
Posts: 6109
    
    6

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

Joined: Sep 20, 2010
Posts: 3647
    
  16

Errr.... yes ^^'
AbdulRab Khan
Greenhorn

Joined: Nov 11, 2011
Posts: 7
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

Joined: Sep 20, 2010
Posts: 3647
    
  16

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

Joined: Mar 17, 2011
Posts: 7831
    
  21

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


Isn't it funny how there's always time and money enough to do it WRONG?
Articles by Winston can be found here
AbdulRab Khan
Greenhorn

Joined: Nov 11, 2011
Posts: 7
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

Joined: Sep 20, 2010
Posts: 3647
    
  16

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

Joined: Sep 20, 2010
Posts: 3647
    
  16

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

Joined: Oct 27, 2005
Posts: 19697
    
  20

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

Err yes. My bad.
Karn Kumar
Ranch Hand

Joined: Aug 06, 2009
Posts: 146

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

Joined: Aug 02, 2011
Posts: 95
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

Joined: Oct 27, 2005
Posts: 19697
    
  20

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

Joined: May 17, 2013
Posts: 36
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

Joined: Aug 02, 2011
Posts: 95
Can Immutable class have a reference to a mutable class ?
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38902
    
  23
Yes, but you have to take defensive copies of any mutable fields if they enter or leave the class.
Santosh Kumar Nayak
Ranch Hand

Joined: Aug 02, 2011
Posts: 95
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

Joined: Oct 13, 2005
Posts: 38902
    
  23
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

Joined: Mar 17, 2011
Posts: 7831
    
  21

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

Joined: Aug 02, 2011
Posts: 95
Can you elaborate as what do you mean by defensive copy of the object.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38902
    
  23
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to make class immutable ?