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.
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
Open Group Certified Distinguished IT Architect. Open Group Certified Master IT Architect. Sun Certified Architect (SCEA).
Bharatesh H Kakamari
Joined: Nov 09, 2000
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.
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.
Joined: Mar 17, 2000
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