aspose file tools*
The moose likes Java in General and the fly likes can we create immutable class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "can we create immutable class " Watch "can we create immutable class " New topic
Author

can we create immutable class

saikrishna cinux
Ranch Hand

Joined: Apr 16, 2005
Posts: 689
why string class is said to be immutable ?

i know about immutable concept
immutable means we cannot change the state of an object
i think we can achive this by using private fileds in a class

is Maths class immutable?
is there any other way to create immutable class?
am i right ?

please correct me


A = HARDWORK B = LUCK/FATE If C=(A+B) then C=SUCCESSFUL IN LIFE else C=FAILURE IN LIFE
SCJP 1.4
Jeroen T Wenting
Ranch Hand

Joined: Apr 21, 2006
Posts: 1847
Originally posted by saikrishna cinux:

i know about immutable concept
immutable means we cannot change the state of an object
i think we can achive this by using private fileds in a class

is Maths class immutable?


Originally posted by saikrishna cinux:

is there any other way to create immutable class?
am i right ?


no, you're wrong. Just using private fields doesn't make a class immutable.

please correct me [/QB]

my pleasure.


42
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
String is said to be immutable because, well it is immutable.

Is this class immutable?



Once this class is instantiated, can you change the state of the object, even though its only field is private? If you can, what do you need to change to make it immutable? That is how you make an immutable class.


"Computer science is no more about computers than astronomy is about telescopes" - Edsger Dijkstra
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

Well I don't know what you are thinking but according to me The class which is final is called as immutable.

Immutable means which cann't be change further.

So once you declare the class as final You cann't extend it..

That makes the class immutable.

and yes most important is

Not to provide any direct access to fields, and keep private all methods that alter the state of the object.

If I am wrong then please correct me..
[ August 23, 2006: Message edited by: Ankur Sharma ]

The Best way to predict your future is to create it - Every great individual common man
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970
Originally posted by Ankur Sharma:
Well I don't know what you are thinking but according to me The class which is final is called as immutable.

Immutable means which cann't be change further.

So once you declare the class as final You cann't extend it..

That makes the class immutable.

If I am wrong then please correct me..


With pleasure!

Immutability is usually taken to mean that the data cannot be changed after instantiation. It has nothing to do with subclassing.

(Later Edit) Well, as others later point out, you should make your class final, if you want it to be immutable, otherwise subclasses might defeat your attempts. But being final is just one feature of an immutable class, and not the most important one.
[ August 24, 2006: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

Originally posted by Ankur Sharma:


and yes most important is

Not to provide any direct access to fields, and keep private all methods that alter the state of the object.

If I am wrong then please correct me..



Well thankx for the concern but I also edited my message... Pls check the above ..

Am I wrong again???
Timothy Sam
Ranch Hand

Joined: Sep 18, 2005
Posts: 746
why string class is said to be immutable ?


Pulling up a quick imagination in my mind... Maybe it's because when you assign a String reference a String value, you don't change a member at all.

String a = "";

changed to

a = "I am a String";

variable a now points to a different object. Perhaps there's nothing in the String class that lets you change its members. But that's just my imagination...


SCJP 1.5
http://devpinoy.org/blogs/lamia/ - http://everypesocounts.com/
Adam Nace
Ranch Hand

Joined: Jul 17, 2006
Posts: 117
The steps you need to follow to make a class immutable always depend on your specific goals for the class.

Sometimes, making all the fields private is enough, as long as you write the methods of the class in such a way that they never modify those fields. Remember, the class writer has direct control over the code within the class, so you only really need to worry about the code OUTSIDE of the class. Making fields private is enough to prevent outside clients from modifying the data in a class. The rest is common sense and careful method design. Don't provide mutators, and make sure accessors return copies of fields.

However, making the fields private and <b>final</b> is even better, because the compiler will detect any code that could possibly change those fields, and complain about them. This is often a good idea, but occasionally can be troublesome when attempting to initialize an object in two stages for example (think deserialization, or also using a builder to create an immutable object).

Sometimes, making the class <b>final</b> IS also important, because somebody could otherwise subclass your so-called immutable object and introduce mutability, either accidentally, or purposely. It's usually a good idea to either make the class final, or make the class package private, and use a factory method of a public class to get instances. The second solution allows you to sub-class the object, but doesn't allow others to sub-class the object. This is again working on the princinple that since you alone control the code of sub-classes, you could ensure all subclasses do not break the immutability just by using common sense when writing sub-classes.

One more thing to consider. Any accessors (those are the getXXX methods) should return copies of the fields they access if the types of those fields are not also immutable. Theoretically, you could return the actual reference, an client could modify the reference, and now you have an object which technically still has all of the same field values it did before, but the data represented by those field objects has changed. This may or may not be an issue, depending on your design.

Remember one thing: Immutability isn't a clearly defined, black and white concept. We must always be clear on WHAT attributes of an object are immutable. For example, the javadoc for java.io.File says that the File object is immutable, however, it has modifier methods such as setReadOnly and an accessor canWrite. One can call setReadOnly, then call canWrite, and notice that the state of the File has changed. Or one could call a method like delete, then call exists and also notice that the state has changed. The immutability that they refered to was the fact that the File always refers to exactly the same file, designated by the same path, whether it exists or not, and this cannot be changed after construction time.

- Adam
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Ankur]: Well thankx for the concern but I also edited my message... Pls check the above ..

To help us have clear conversations here, it would probably be better to post new information in new posts, rather than editing old ones. You're making it harder for people to understand the responses to the original post.

[Ankur]: Am I wrong again???

Yes. Making a class final is necessary* to have an immutable class, but not at all sufficient. Adam's post addresses the additional concepts you are missing.

* Well some may argue it's not necessary, since there are alternatives, and some definitions of immutability might allow for mutable subclasses. But most of us would regard it as a good idea at least. There are additional issues which could be debated here, but at this point I think the original poster just needs a basic understanding.


"I'm not back." - Bill Harding, Twister
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
ln -s referential_transparency immutable_questions


Tony Morris
Java Q&A (FAQ, Trivia)
Shaan Shar
Ranch Hand

Joined: Dec 27, 2005
Posts: 1249

Originally posted by Tony Morris:
ln -s referential_transparency immutable_questions


what's this Tony??

Could you come up with details what do you mean by above..
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Ankur Sharma:


what's this Tony??

Could you come up with details what do you mean by above..


man ln
It means one needs to know what referential transparency is before knowing what immutability is. There are many who are quick to define immutability without the slightest understanding of the mathematic definition of a function - one of the axioms of immutability, hence, I used UNIX terminology to create a "soft link".

The best - though still incomplete - definition of immutability in this context that I have encountered so far is by Erik Poll in a document titled "Immutable objects in Java".
Rusty Shackleford
Ranch Hand

Joined: Jan 03, 2006
Posts: 490
Is the context of the original question, a mathematical background is not necessary to explain nor understand. It is like a college algebra or calculus course, an intuitive understanding of a function is all that you need. Not long after calculus that understanding is not useful and a more rigorous one is needed. Not that a rigorous definition of a function is all that difficult to understand.
[ August 24, 2006: Message edited by: Rusty Shackleford ]
Eitan Levi
Greenhorn

Joined: Jun 14, 2006
Posts: 14
There's a great article on IBM's DeveloperWorks that talks about how to create an immutable class, and expands on what Adam said above: http://www-128.ibm.com/developerworks/java/library/j-jtp02183.html

It has nothing to do with declaring the class itself as final, but everything to do with making sure that its members can't change during the lifetime of the class. This means that you declare your members final, which means you can only assign to them in the constructor. It also means that you never return a reference to an object in a get() method, but instead a reference to a clone of the object.
[ August 24, 2006: Message edited by: Eitan Levi ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Is a class immutable if some of its members are mutable and accessible by get? Surely not using Tony's referential transparency as you could call one method twice and get different results. So all private variables and no set methods is not enough yet. I'm liking Tony's test for immutable better all the time, though it doesn't mechanically translate into how to code one.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18121
    
    8

Okay. So, for example, is java.util.Random immutable? It doesn't have any "setter" methods, or any other method whereby other classes could affect the state of a Random object, as far as I can see. But it thoroughly fails the referential transparency test.

Edit: I didn't look and think hard enough. Clearly the methods nextInt() and nextDouble() and so on are setter methods, even though no information is passed by the callers of those methods.
[ August 24, 2006: Message edited by: Paul Clapham ]
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
I think you're overlooking the setSeed() method, Paul, an even more explicit setter method.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Rusty Shackleford:
Is the context of the original question, a mathematical background is not necessary to explain nor understand. It is like a college algebra or calculus course, an intuitive understanding of a function is all that you need. Not long after calculus that understanding is not useful and a more rigorous one is needed. Not that a rigorous definition of a function is all that difficult to understand.

[ August 24, 2006: Message edited by: Rusty Shackleford ]


One day, I hope this will no longer hold *and* be immediately obvious to the general population. I will continue to push for the appropriate education courses at the university I work at.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Stan James:
Is a class immutable if some of its members are mutable and accessible by get? Surely not using Tony's referential transparency as you could call one method twice and get different results. So all private variables and no set methods is not enough yet. I'm liking Tony's test for immutable better all the time, though it doesn't mechanically translate into how to code one.


Looking at Erik Poll's work my definition of immutability aligns with his definition of "Observational Immutability". Poll also goes on to distinguish between "State-based Immutability" (which I claim is horribly flawed and is not worthy of having a name - Poll instead says it makes no guarantees but at least has a formal definition) and Shallow Immutability and Deep Immutability - both of which I think are missing some crucial points to provide a complete understanding of the topics.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Paul Clapham:
Okay. So, for example, is java.util.Random immutable? It doesn't have any "setter" methods, or any other method whereby other classes could affect the state of a Random object, as far as I can see. But it thoroughly fails the referential transparency test.

Edit: I didn't look and think hard enough. Clearly the methods nextInt() and nextDouble() and so on are setter methods, even though no information is passed by the callers of those methods.

[ August 24, 2006: Message edited by: Paul Clapham ]


No it is not immutable - it can have some observable state change to "the world" (I prefer "the universe" but the generally accepted term is the world).

To answer your question thoroughly, you might consider looking at category theory and how monads (hint: search term) solve the problems of observable world state "change" in functional languages. Consider the problem of entering some input from the keyboard: Input getInput(); clearly this is not a function, since Input may be observed to change. Note that if it were referentially transparent, it would be called a "constant function" since it accepts no parameters - which is related to how I use Java. When a client binds to implementation I ensure that they bind to a constant function - a static method that accepts no parameters and returns a referentially transparent (shallow immutable in Poll's terms) type. You may have seen me post some code of this nature previously but fail to justify its verbosity (imposed by Java to reduce complexity) - I hope you can understand why - the audience requires an understanding of monads, FP, a critical analysis of OO and many other topics before this justification can even begin.

I use the term "change" loosely since some will claim that change does not occur - that the world is immutable - what appears as "change" is in fact a "new world". A revision control system demonstrates the immutable world in some ways.

That ends my rant - have a good weekend
[ August 24, 2006: Message edited by: Tony Morris ]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Thanks, the Poll PDF was interesting. His "state based" definition might be useful just so some of us can say "Yes, that's what I meant" before going on to more rigorous definitions.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: can we create immutable class
 
Similar Threads
Math
immutable class
immutable
Immutable Entities
wrapper class