Java Reference
In-Depth Information
As you saw in the summary at the beginning of this section, the protected method clone() that is inherited
from the Object class creates a new object that is a copy of the current object. It does this only 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 — you learn about 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 corres-
ponding 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 isn't typically what you want to happen — both
the old and the new class objects can now be modifying a single shared mutable object that is referenced
through their corresponding data members, not recognizing that this is occurring.
Using the clone() method to duplicate objects can be complicated and cumbersome. If you need to clone
objects of your class types, the simplest approach is to ignore the clone() method and implement a copy
constructor in your class. A copy constructor is just a constructor that duplicates an object that is passed as
an argument to it. Let's look at an example to see how duplicating objects using a copy constructor works.
TRY IT OUT: Duplicating Objects
Let's suppose you define a class Flea like this:
public class Flea extends Animal {
// Constructor
public Flea(String aName, String aSpecies) {
super("Flea");
// Pass the type to the base
name = aName;
// Supplied name
species = aSpecies;
// Supplied species
}
// Copy Constructor
public Flea(Flea flea) {
super(flea);
// Call the base class copy constructor
name = flea.name;
species = flea.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;
}
Search WWH ::




Custom Search