Java Reference
In-Depth Information
Choosing a name for your pet's flea has changed the name for my pet's flea too. Unless you really want
to share objects between the variables in two separate objects, you should implement the clone()
method in your class to do the cloning the way you want. As an alternative to cloning (or in addition to)
you could add a constructor to your class to create a new class object from an existing object. This
creates a duplicate of the original object properly. You saw how you can do this in the previous chapter.
If you implement your own public version of clone() to override the inherited version, you would
typically code this method in the same way as you would the constructor to create a copy of an object.
You could implement the clone() method in the PetDog class like this:
public Object clone() throws CloneNotSupportedException {
PetDog pet = new PetDog(name, breed);
pet.setName("Gnasher");
pet.getFlea().setName("Atlas");
return pet;
}
Here the method creates a new PetDog object using the name and breed of the current object. We then
call the two objects' setName() methods to set the clones' names. If you compile and run the program,
again with this change, altering the name of myPet will not affect yourPet . Of course, you could use
the inherited clone() method to duplicate the current object, and then explicitly clone the Flea
member to refer to an independent object:
// Override inherited clone() to make it public
public Object clone() throws CloneNotSupportedException {
PetDog pet = (PetDog)super.clone();
pet.petFlea = (Flea)petFlea.clone();
return pet;
}
The new object created by the inherited clone() method is of type PetDog , but it is returned as a
reference of type Object . In order to access the thePet member, we need a reference of type PetDog
so the cast is essential. The same is true of our cloned Flea object. The effect of this version of the
clone() method is the same as the previous version.
Casting Objects
You can cast an object to another class type, but only if the current object type and the new class type
are in the same hierarchy of derived classes, and one is a superclass of the other. For example, earlier in
this chapter we defined the classes Animal , Dog , Spaniel , Cat and Duck , and these classes are
related in the hierarchy shown below:
Search WWH ::




Custom Search