Immutable Object
Immutable Object
String s = "ABC";
s.toLowerCase();
The method toLowerCase() will not change the data "ABC" that s contains.
Instead, a new String object is instantiated and given the data "abc" during its
construction. A reference to this String object is returned by the toLowerCase()
method. To make the String s contain the data "abc", a different approach is
needed.
s = s.toLowerCase();
Now the String s references a new String object that contains "abc". The String
class's methods never affect the data that a String object contains.
class Cart {
private final List items;
An instance of this class is not immutable: one can add or remove items either
by obtaining the field items by calling getItems() or by retaining a reference
to the List object passed when an object of this class is created. The following
change partially solves this problem. In the ImmutableCart class, the list is
immutable: you cannot add or remove items. However, there is no guarantee
that the items are also immutable. One solution is to use the decorator pattern
as a wrapper around each of the list's items to make them also immutable.
class ImmutableCart {
private final List items;