"Hi, Amigo!"
"Hi, Bilaabo!"
"Today Bilaabo will tell you about mutable and immutable objects.
"Objects you can change after they are created are called mutable."
"Objects that cannot be changed after they are created are called immutable."
"What determines whether I can change an object?"
"The author of a new class can make objects of that class immutable. For example, if you make all of the setters private, then an object will only have a constructor and getters; that means it will be impossible to change after it is created."
"And what would be the point of that?"
"Immutable objects have many useful properties, but I'll highlight two that are common to almost all immutable objects:"
1) Immutable objects are much easier to implement than mutable objects.
2) Immutable objects can be freely used across multiple threads simultaneously.
"When a developer decides to write an immutable class, he usually makes both a mutable and immutable version of the class."
"But what's the point of writing two classes instead of one?"
"Sometimes it's worth it when an immutable version of an object will be far simpler/faster than a mutable one. So, they make two versions. It's kind of like ArrayList and LinkedList: both are lists, but one is optimized for specific purposes, and the second for others."
"That makes more sense already."
"There are also purely immutable classes, which don't have a mutable version."
"But what if I need to change something in one of those objects? What can you actually do with an immutable object?"
"Usually, immutable classes contain various methods that act like they change the object, but these methods simply create a new object and return it, instead of changing the object itself."
"Here are some examples:"
Java code | Description |
---|---|
|
As a result, s contains the string «london» and s2 contains «LONDON» |
|
Here's what really happens: Integer i = new Integer(1); Integer j = i; j = new Integer(i.getInt()+1); |
"The String class is an immutable class. All String objects are immutable, but that doesn't keep us from working with them. For example, the toUpperCase() method of the String class converts a String to uppercase (i.e. replaces all small letters with capital letters). However, this method doesn't change the String itself, instead it returns a new String. This new String is identical to the first except all the characters are uppercase (capital letters)."
"The Integer class is also an immutable class. All Integer objects are immutable. Every time we change an Integer object, we are actually creating a new object."
"How interesting! Hooray, Bilaabo."
"Hooray for me! Hooray for Bilaabo!"
GO TO FULL VERSION