I’m trying to perform a deep copy of an object in which the new object is then modified without altering the oringial. To test the functionaility i’m using JUnit to ensure the functionaility works.
The current test is a basically copying the game “Mass Effect 3” and altering the current voice actor.
Game Class
@Override
protected Object clone(){
Game obj = new Game(getTitle(), getLeadVoiceActor(), getRating());
return obj;
}
JUnit Tests
@Before
public void setUp() {
p1 = new Person("Mark", "Meer");
g1 = new Game("Mass Effect 3", p1, 5);
}
@Test
public void testClone() throws CloneNotSupportedException {
//This works
Game g2 = (Game)g1.clone();
assertEquals(g2, g1);
assertNotSame(g2, g1);
//This doesn't even though the lead voice actor is now different
p1 = g1.getLeadVoiceActor();
p1.setFirstName("Jennifer");
p1.setLastName("Hale");
assertFalse(g2.equals(g1));
assertEquals("Jennifer Hale", g1.getLeadVoiceActor().toString());
assertEquals("Mark Meer", g2.getLeadVoiceActor().toString());
}
The test is failing with junit.framework.assertionfailederror.
If your question is: why are the person in the original game and the person in the cloned game the same?, then the answer is that you’re not deep cloning but shallow cloning.
Calling
getLeadVoiceActor()and assigning the result to the cloned game passes a reference to the person to the cloned game. It doesn’t make any copy. To make a copy, you would needor
Note that the use of
clone()is discouraged in favor of copy constructors. And if you implement clone, than you should usesuper.clone().Also note that you wouldn’t have to clone the Person if it was immutable.