Clone Java objects

Posted: October 7, 2009 in Uncategorized
Tags:

Since objects in Java are manipulated through reference variables, there is no direct way to copy an object. Classes that want copying functionality must implement clone() method to do so. This guide shows how to make a Java class Cloneable and perform a cloning.

A class to be cloned:

class Person {
    private String firstName;
    private String lastName;

    private Person assistant;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setAssistant(Person assistant) {
        this.assistant = assistant;
    }
	
	public Person getAssistant() {
		return assistant;
	}
}

Todos:

  • implementing the Cloneable interface
  • make Object clone() method public (by overriding the protected method)
  • call the clone method defined in Object base class (to create a shallow copy of the object)
  • deep copy (clone) all mutable objects in case a reference copy is not enough

Our cloneable class:

class Person implements Cloneable {
    private String firstName;
    private String lastName;

    private Person assistant;

    public Person(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public void setAssistant(Person assistant) {
        this.assistant = assistant;
    }

    public Person getAssistant() {
        return assistant;
    }

    public Object clone() throws CloneNotSupportedException {
        Person cloned = (Person) super.clone();

        /*
              If we don't do anything else, the cloned person 
			  will refer to the to the same assistant object 
			  as the original person.

              In this example we want to avoid that
			  and make a deep copy of the assistant object as well.
          */
        if (this.assistant != null)
            cloned.assistant = (Person) this.assistant.clone();
        return cloned;
    }
}

How to clone:

public class Test {
    public static void main(String[] args) {
        try {
            Person john = new Person("John", "Doe");
            Person bob = new Person("Bob", "Gombocki");
            john.setAssistant(bob);
            Person johnsClone = (Person) john.clone();
            System.out.println("John is cloned: " + (john != johnsClone));
            System.out.println("John's assistant, Bob is cloned: " + (john.getAssistant() != johnsClone.getAssistant()));
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s