• Post Reply Bookmark Topic Watch Topic
  • New Topic

Wrapper Class Immutability.  RSS feed

 
Pankaj Shet
Ranch Hand
Posts: 320
Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ranchers,

Can anyone give me detailed explanation for why Wrapper Classes are Immutable?

Regards,
-Pankaj Shet

 
Marco Ehrentreich
best scout
Bartender
Posts: 1294
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Pankaj,

I don't know if there is any explicit statement why these classes are immutable in Java but in general it is much easier to use such core classes if they are immutable (and final). If they would be mutable like java.util.Date for example you would have to take much more care about data consistency issues when designing your own classes. For example every naive getter for a Date field leaks the state of an object even if the field is private. To prevent such issues you have to make defensive copies and much more. Handling equals() and hashCode() correctly becomes easier with immutable classes, too. Additionally there are technical reasons for immutability I guess, like caching numeric objects which the JVM does for a small range of values.

As I wrote above the wrapper classes and some core classes like String are also final because the designers of Java decided that it would be too dangerous to allow every programmer to change the behavior of these core classes by subclassing them.

Marco
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!