aspose file tools*
The moose likes Beginning Java and the fly likes About imutable class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "About imutable class" Watch "About imutable class" New topic
Author

About imutable class

Pradyumna Khadanga
Greenhorn

Joined: Aug 18, 2009
Posts: 5
One of the interviewer asked me "How to write a custom Imutable class ?"
For this what is the exact answer ?
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61224
    
  66

What is your answer?


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

Bear Bibeault wrote:What is your answer?
Jelle Klap
Bartender

Joined: Mar 10, 2008
Posts: 1763
    
    7

An immutable class?

Build a man a fire, and he'll be warm for a day. Set a man on fire, and he'll be warm for the rest of his life.
Pradyumna Khadanga
Greenhorn

Joined: Aug 18, 2009
Posts: 5
Hi friend I answered him that
Just make all the fields private and don't write any method in that class which has capability to change the state of that object .
and other wise you can make the class singleton.
Thanks to reply me
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
Disagree. There is no need to use the singleton pattern at all.
All the fields should be final.
The class should be final so it cannot be extended and the subclass altered.
There should be no "set" methods.
Any "get" methods which return primitives or immutable reference types can be unchanged.
Any "get" methods which return mutable reference types should return a defensive copy.
Any methods which might change the state of the object should instead create a new object with the altered state.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Pradyumna Khadanga wrote:Hi friend I answered him that
Just make all the fields private and don't write any method in that class which has capability to change the state of that object .
and other wise you can make the class singleton.
Thanks to reply me


Umm, no. As Campbell said, the Singleton pattern doesn't really have anything to do with immutability. A good example of an immutable class is String. String clearly is not a singleton.

John.
Pradyumna Khadanga
Greenhorn

Joined: Aug 18, 2009
Posts: 5
Thanks for your answer ,it will give me a lots of idea . Since i am new to java , I put this Q here .
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38881
    
  23
It would be the same answer in other languages.
Embla Tingeling
Ranch Hand

Joined: Oct 22, 2009
Posts: 237
Pradyumna Khadanga wrote:One of the interviewer asked me "How to write a custom Imutable class ?"
For this what is the exact answer ?


The exact answer is: Don't make it mutable.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About imutable class