Java Reference
In-Depth Information
Note: Java's class String is a read-only class. That is, instances of String are immutable.
Once you create a string, you cannot change it. Frequently, however, string applications
require that you either remove a portion of a string or join two strings together. For such
applications, Java provides the class StringBuilder of mutable strings. StringBuilder pro-
vides several methods that modify a string by adding, removing, or replacing substrings.
Appendix A describes some of the methods that belong to these two classes.
String and StringBuilder are a pair of companion classes. String has a constructor that
takes an instance of StringBuilder as an argument and produces an immutable string with the
same value. StringBuilder has an analogous constructor that creates mutable strings from
immutable ones. StringBuilder also has the methods substring and toString that return
instances of String .
Cloneable Objects
30.12
In Segment 30.4, we created a sorted list of mutable objects. Unfortunately, the client of this list can
modify the objects so that they are no longer sorted. As you saw then, one solution is to always place
immutable objects in a sorted list.
A more involved solution has the sorted list copy the client's objects. The sorted list then can
control what the client can and cannot do to the copies. This section examines how to make a copy
of an object.
VideoNote
Cloneable objects
30.13
In Java, a clone is a copy of an object. Typically, we clone only mutable objects. Since sharing an
immutable object is safe, cloning it is usually unnecessary.
The class Object contains a protected method clone that returns a copy of an object. The
method has the following header:
protected Object clone() throws CloneNotSupportedException
Since clone is protected, and since Object is the superclass of all other classes, the implemen-
tation of any method can contain the invocation
super .clone()
But clients of a class cannot invoke clone unless the class overrides it and declares it public. Making
copies of objects can be expensive, so it might be something you do not want a class to do. By making
clone a protected method, the designers of Java force you to think twice about cloning.
Programming Tip: Not all classes should have a public clone method. In fact, most
classes, including read-only classes, do not have one.
30.14
If you want your class to contain a public method clone , the class needs to state this fact by imple-
menting the Java interface Cloneable , which is in the package java.lang of the Java Class Library.
Such a class would begin as follows:
public class MyClass implements Cloneable
{ . . .
The interface Cloneable is simply
public interface Cloneable
{
}
 
Search WWH ::




Custom Search