Clone Java objects

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 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 real copy
		of the assistant object as well.
          */
        if (this.assistant != null)
            cloned.assistant = (Person) this.assistant.clone();
        return cloned;
    }
}

Note: deep copying can be risky if there is a circular reference as it can produce an endless loop of cloning. Those cases need special attention. In this concrete example it’s not a problem, we assumed that the „assistant“ relationship is not reflexive.

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();
        }
    }
}

Popularity: 1% [?]

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

You can leave a response, or trackback from your own site.

Leave a Reply

Задвижван с помощта на WordPress | Compare Cell Phone Plans at iCellPhonePlans.com | Thanks to Cheap Palm Pixi, Bromoney and Wordpress Themes