Java Reference
In-Depth Information
yourPet.setName("Gnasher");
Your dog will probably like a personalized flea too, so we can change the name of its flea with the statement:
yourPet.getFlea().setName("Atlas");
Unfortunately Fang 's flea will also be given the name Atlas because, under the covers, Fang and
Gnasher both share a common Flea . If you want to demonstrate this, you can put all the classes
together in an example, with the following class:
// Test cloning
public class TestFlea {
public static void main(String[] args) {
try {
PetDog myPet = new PetDog("Fang", "Chihuahua");
PetDog yourPet = (PetDog)myPet.clone();
yourPet.setName("Gnasher"); // Change your dog's name
yourPet.getFlea().setName("Atlas"); // Change your dog's flea's name
System.out.println("\nYour pet details:\n"+yourPet);
System.out.println("\nMy pet details:\n"+ myPet);
} catch(CloneNotSupportedException e) {
e.printStackTrace(System.err);
}
}
}
Don't worry about the try and catch blocks - these are necessary to deal with the exception that we
mentioned earlier. You will learn all about exceptions in Chapter 7. Just concentrate on the code between the
braces following try . If you run the example it will output the details on myPet and yourPet after the
name for yourPet has been changed. Both names will be the same so the output will be:
C:\Java\3668\Ch06\TestFlea>java TestFlea
Your pet details:
This is a Dog
It's Gnasher the Chihuahua &
This is a Flea
It's Atlas the circus flea
My pet details:
This is a Dog
It's Fang the Chihuahua &
This is a Flea
It's Atlas the circus flea
Search WWH ::




Custom Search