PDA

View Full Version : deep copy


uniquity
01-29-2009, 10:59 PM
for my 102 class, i'm supposed to make a bunch of classes that represent shapes, with a parent AbstractShape class. within these classes, i'm supposed to create deep copies of certain variables. unfortunately, my teacher is on sick leave until the end of this week so i can't ask him for help :rolleyes: but i was wondering if anyone could explain to me when exactly (or what) i'm supposed to be making deep copies of, and how to do so. i've tried googling it, but most of the stuff that comes up is a little beyond my current knowledge of java :confused: thanks in advance for any help

uniquity
01-30-2009, 09:47 PM
anyone??? i just need some tips or pointers for how to make a deep copy through the constructor. any help right now would be greatly appreciated.

Fou-Lu
01-31-2009, 01:16 AM
I thought I answered this one >.<
Deep copying refers to copying a referenced object as opposed to keeping the reference. Java has a clone() function which performs a shallow copy - copies any primitive and retains the pointers to the object properties. Any change in the original or the copy will effect both of the objects. I would override the clone method by implementing Cloneable interface. Hold on I'll find an example online. This one looks pretty good, they have used clone for shallow copies and created a deepClone method for deep ones: http://www.idevelopment.info/data/Programming/java/object_oriented_techniques/CloningExample.java

Hope that helps!

uniquity
01-31-2009, 01:20 AM
thanks for the reply fou-lu! unfortunately, my professor supplied us with a test driver which fails our program unless it complies with the architecture that he "specifies" and upon implementing the Cloneable interface or even adding the method clone() fails the architecture tests as specified in the test driver. are there any other ways to clone?

p.s. i've tried serializing as well, but same result as above :(

Fou-Lu
01-31-2009, 02:49 PM
Yes, you can create a cloning constructor.
The logic is the same as using the clone method, you just create a constructor that takes in an instance of the same object type and copies each value that way. The only differences between this route and clone is that you need to copy from argvOther into this, instead of copying this into this. That and the call would be more like MyObj clone = new MyObj(originalMyObj);.