October 24, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Object Integrity & Security: Duplicating Objects, Part 3

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

When you run this application using the code in Listing 5, you get a curious result.

Listing 5: The application class with the Head class

// Class Duplicate
public class Duplicate {

   public static void main(String[] args) {

      Dog fido = new Dog("fido", "retriever", "black");

      System.out.print("fido :  = ");
      System.out.print("name  = " + fido.getName());
      System.out.print(", breed = " + fido.getBreed());
      System.out.println(", nose = " + fido.head.getNose());


      Dog spot;

      spot = (Dog)fido.copy("spot", "mutt", "pink");

      System.out.print("fido :  = ");
      System.out.print("name  = " + fido.getName());
      System.out.print(", breed = " + fido.getBreed());
      System.out.println(", nose = " + fido.head.getNose());

      System.out.print("spot :  = ");
      System.out.print("name  = " + spot.getName());
      System.out.print(", breed = " + spot.getBreed());
      System.out.println(", nose = " + spot.head.getNose());

   }

}

Note that you have added the following line of code to the application in an attempt to give Fido a black nose and Spot a pink nose.

Dog fido = new Dog("fido", "retriever", "black");

....

spot = (Dog)fido.copy("spot", "mutt", "pink");

However, when you run this, you get the results seen in Figure 2.



Click here for a larger image.

Figure 2. Providing some color

Notice how fido originally has the correct node color, black. However, after you cloned the object and then set Spot's nose color to 'pink', fido's object is now 'pink' as well, incorrectly so.

This perfectly illustrates the problem of duplicating objects. It appears that you are, again, duplicating just the reference to the Head object and not actually creating a new one—as intended. As seen in Diagram 3, you may have two totally separate objects, fido and spot; however, they seem to reference the same head object. This is a situation that may cause major problems unless proper testing is performed.

Diagram 3: A Single Head Object





Page 4 of 5



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel