October 19, 2019
Hot Topics:

Object Integrity & Security: Duplicating Objects, Part 3

  • July 6, 2007
  • By Matt Weisfeld
  • Send Email »
  • More Articles »

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();


      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.

Page 3 of 5

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date