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 »

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.





Page 3 of 5



Comment and Contribute

 


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

 

 


Sitemap | Contact Us

Rocket Fuel