Chapter 3. Immutable Types
The source of one of the most persistent
problems encountered in Java is the fact that variables for
constructed types are always references, and
these references are passed by value. Essentially, this allows anyone
with a reference to the object to change the object. Although this
may not be bad in some circumstances, it would be disastrous in
others. If one part of the program is expecting data to be in an
object, and another part of the program alters that data to be
null
, the program would crash with
NullPointerException
s. Since the part of the
program that changed the data object is different from the part that
generated the exceptions, the bug could be very difficult to locate.
One approach to this problem is to make the data object an instance of a class that cannot be changed after construction; these types are referred to as immutable types. Instances of immutable types are called immutable objects . If your data object is an immutable object, the other classes using the object simply have no way to change the data in the object. This is the main advantage of immutable objects; you can pass their references all over the place without having to worry about breaking encapsulation or thread safety.
Although immutable objects exist in many languages, they take on a more serious role in Java. Like virtual shoelaces, they tie together the language of Java without getting much credit. However, the conscious and correct usage of immutable types is often ...
Get Hardcore Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.