August 27, 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 »

Consider the fact that if you want to create a second dog object called spot, you could simply create an entirely new object called spot, just as you did for the object fido.

Dog spot = new Dog("spot", "mutt");

This works fine. In fact, it may very well work better in a simple case. However, assume that you have an entire litter of dogs, and the Dog class identifies 25 different attributes. If each puppy in the litter shares 20 of the attributes, with only 5 that vary, it may make sense to completely clone the objects from a standard object and then make the few changes for each. This saves you the hassle of initializing each of the 20 attributes that they share.

As in many programming scenarios, you can take this even further and see what happens if you want to copy 1,000 objects that share most of their attributes, or 1,000,000? In short, it all depends on the application.

Listing 2: The Previous Example (Duplicate.java)

// Class Duplicate
public class Duplicate {

   public static void main(String[] args) {

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

      Dog spot;

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

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

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

   }

}

This code has evolved through several iterations to the point where an object can be cloned, and then its attributes can be initialized to unique values (please reference the previous two articles in this series).

Diagram 1 illustrates what is actually happening here. The original object, fido, is cloned. Cloning fido creates the second object, spot; however, cloning implies that both objects are identical and you do not want the second object to have the same exact attributes as the first. Thus, you provide a copy() method in the class that allows you to create a totally new object, but with unique attributes. In Diagram 1, you see that there are two totally separate objects and each has its own name.

Diagram 1: An Object with two References and two Objects (different content)

You can prove that this is working the way You intend simply by executing the code. The results are found in Figure 1.

Figure 1: Using the copy() method





Page 2 of 5



Comment and Contribute

 


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

 

 


Sitemap | Contact Us

Rocket Fuel