Java Reference
In-Depth Information
It looks as though we could use a mutator method from the class String to change
the name referenced by nameAlias and so violate the privacy of the instance variable
name . Is something wrong? Do we have to rewrite the method getName to use the copy
constructor for the class String ? No, everything is fine. We cannot use a mutator
method with nameAlias because the class String has no mutator methods! The class
String contains no methods that change any of the data in a String object.
At first, it may seem as though you can change the data in an object of the class
String . What about the string processing we have seen, such as the following?
String greeting = "Hello";
greeting = greeting + "friend.";
Have we not changed the data in the String object from "Hello" to "Hello
friend." ? No, we have not. The expression greeting + "friend." does not change
the object "Hello" ; it creates a new object, so the assignment statement
greeting = greeting + "friend.";
replaces the reference to "Hello" with a reference to the different String object
"Hello friend." The object "Hello" is unchanged. To see that this is true, consider
the following code:
String greeting = "Hello";
String helloVariable = greeting;
greeting = greeting + "friend.";
System.out.println(helloVariable);
This produces the output "Hello" . If the object "Hello" had been changed, the
output would have been "Hello friend."
A class that contains no methods (other than constructors) that change any of the
data in an object of the class is called an immutable class , and objects of the class are
called immutable objects . The class String is an immutable class. It is perfectly safe
to return a reference to an immutable object, because the object cannot be changed in
any undesirable way; in fact, it cannot be changed in any way whatsoever.
A class that contains public mutator methods or other public methods, such as
input methods, that can change the data in an object of the class is called a mutable
class , and objects of the class are called mutable objects . The class Date is an example
of a mutable class; many, perhaps most, of the classes you define will be mutable
classes. As we noted in the Pitfall entitled “Privacy Leaks” (but using other words): You
should never write a method that returns a mutable object, but should instead use a
copy constructor (or other means) to return a reference to a completely independent
copy of the mutable object.
immutable
mutable
 
Search WWH ::




Custom Search