Object Integrity & Security: Duplicating Objects, Part 3
A Single Head
For this iteration, you will add another class called Head.
Listing 3: Adding the Headclass
// Class Head
class Head {
String nose;
public Head(String n) {
nose = n;
}
public String getNose() {
return nose;
}
public void setNose(String n) {
nose = n;
}
}

Diagram 2: UML Diagram
You use composition to include the Head class as part of a Dog, as you can see in UML Class shown in Diagram 2. Again, you are using this as a simple example to illustrate the process of cloning/copying objects. An argument can be made that you should not be using a term like nose to represent an attribute. If nose is actually considered a separate object, perhaps you should make it an object unto itself. I just want to point out that, in some designs, you may want to name the attribute something like noseColor.
The deciding factor here would be whether or not you want to reuse a nose object and whether or not nose is made up of other attributes. Even though it might not sound like it, this is an interesting discussion unto itself, and I will leave this discussion for another day.
Listing 4: The Dog class with the Head class
// Class Dog
class Dog implements Cloneable {
String name;
String breed;
Dog ref;
Head head;
public Dog(String n, String b, String s) {
name = n;
breed = b;
head = new Head(s);
}
public Dog copy(String n, String b, String s) {
ref = (Dog)clone();
ref.setName(n);
ref.setBreed(b);
ref.head.setNose(s);
return ref;
}
public Object clone() {
try {
System.out.println("Inside clone");
return super.clone();
} catch (CloneNotSupportedException e) {
throw new InternalError(e.toString());
}
}
public String getName() {
return name;
}
public void setName(String n) {
name = n;
}
public String getBreed() {
return breed;
}
public void setBreed(String b) {
breed = b;
}
}
When you run this application using the code in Listing 5, you get a curious result.
More for Developers
On the Codeguru Forums
Visit the Forums »Featured Partner Resources
Get your Android Apps ready for Intel® Atom™ processor-based smartphones and tablets now.
Use the Android NDK to deliver the best performance on Intel® Atom™ processor-based devices.
The Android community on the Intel® Software Network has everything you need to prepare your apps for Intel® Atom™ processor-based devices.



Solid state disks (SSDs) made a splash in consumer technology, and now the technology has its eyes on the enterprise storage market. Download this eBook to see what SSDs can do for your infrastructure and review the pros and cons of this potentially game-changing storage technology.