Java Reference
In-Depth Information
Copying Objects
As you saw in the summary at the beginning of this section, the protected method, clone() , that is
inherited from the Object class will create a new object that is a copy of the current object. It will only
do this if the class of the object to be cloned indicates that cloning is acceptable. This is the case if the
class implements the Cloneable interface. Don't worry about what an interface is at this point - we
will look into this a little later in this chapter.
The clone() method that is inherited from Object clones an object by creating a new object of the
same type as the current object, and setting each of the fields in the new object to the same value as the
corresponding fields in the current object. When the data members of the original object refer to class
objects, the objects referred to are not duplicated when the clone is created - only the references are
copied from the fields in the old object to the fields in the cloned object. This is not typically what you
want to happen - both the old and the new class objects can now be modifying a single shared object
that is referenced through their corresponding data members, and not recognizing that this is occurring.
If objects are to be cloned, the class must implement the Cloneable interface. We will discuss interfaces
later in this chapter where we will see that implementing an interface typically involves implementing a
specific set of methods. All that is required to make a class implement this interface is to declare it in the first
line of the class definition. This is done using the implements keyword - for example:
class Dog implements Cloneable {
// Details of the definition of the class...
}
This makes Dog objects cloneable since we have declared that the class implements the interface.
We can understand the implications of the inherited clone() method more clearly if we take a simple
specific instance. Let's suppose we define a class Flea that has a method that allows the name to be changed:
public class Flea extends Animal implements Cloneable {
// Constructor
public Flea(String aName, String aSpecies) {
super("Flea"); // Pass the type to the base
name = aName; // Supplied name
species = aSpecies; // Supplied species
}
// Change the flea's name
public void setName(String aName) {
name = aName; // Change to the new name
}
// Return the flea's name
public String getName() {
return name;
}
// Return the species
public String getSpecies() {
Search WWH ::




Custom Search