File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Ajith please clarify

 
Bharatesh H Kakamari
Ranch Hand
Posts: 198
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the post of subject 'few basic questions' moved to Java beginner forum the answer for 4 was : Math class is immutable because it cannot be instantiated.
My doubts are :
i) what is the difference between immutable and final. According to my understanding immutable is one whose contents / value do not change. But final is one which cannot be subclassed. String class is both final and immutable. But Math class is final. But because the constructor is private, one cannot instantiate it.
ii) how does a class be designed to be immutable so as to make the object instanstiated to be immutable.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You may want to read this discussion where I have attempted to differentiate immutable classes from final classes.
Immutable classes can be implemented by not providing "mutator" methods( aka set() methods ). The designer can make all the data members private and provide a few overloaded constructors as the only way to "put" initial value into the object. Checkout the methods and constructors for classes such as Long or Double or String and you'll understand what I mean.
Hope that helps,
Ajith
 
Bharatesh H Kakamari
Ranch Hand
Posts: 198
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the link and the explanation. It made it more easier for me to understand the difference. I got confused as one mock exam says Math class is not Immutable.
 
Hemant Bhaiya
Greenhorn
Posts: 21
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ajith,
I read the explanation given by you about immutability.It's nice.
But I am still confused whether Math class is immmutable or not.
Immutable means once assigned a value in a constructor then it can't be changed.In Math class we can't invoke a constructor and so there is no question of changing it.
Is Math immutable.
 
Ajith Kallambella
Sheriff
Posts: 5782
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hemanth,
The answer to your question is YES!!
Math and other wrapper classes such as Long, Double, Boolean etc are all immutable. Once you create them with a value, you will never be able to make the same object hold a different value. Try it for yourself.
Ajith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic