Java Reference
In-Depth Information
// Return the breed
public String getBreed() {
return breed;
}
// Return the flea
public Flea getFlea() {
return petFlea;
}
public void sound() {
System.out.println("Woof");
}
// Return a String for the pet dog
public String toString() {
return super.toString() + "\nIt's " + name + " the "
+ breed + " & \n" + petFlea;
}
// Override inherited clone() to make it public
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
private Flea petFlea; // The pet flea
private String name; // Dog's name
private String breed; // Dog's breed
}
To make it possible to clone a PetDog object, we override the inherited clone() method with a
public version that calls the base class version. Note that the inherited method throws the
CloneNotSupportedException so we must declare the method as shown - otherwise it won't
compile. We will be looking into what exceptions are in the next chapter.
We can now create a PetDog object with the statement:
PetDog myPet = new PetDog("Fang", "Chihuahua");
After seeing my pet, you want one just like it, so we can clone him:
PetDog yourPet = (PetDog)myPet.clone();
Now we have individual PetDog objects that regrettably contain references to the same Flea object.
The clone() method will create the new PetDog object, yourPet , and copy the reference to the
Flea object from the myPet data member in myPet to the member with the same name in yourPet .
If you decide that you prefer the name " Gnasher " for yourPet , we can change the name of your pet
with the statement:
Search WWH ::




Custom Search