Jul 252017

ADM

How to clone an object in Java

  • 25 July 2017
  • ADM

 

 

 

How to clone an object in Java - images/logos/java.jpg

 

In this article will present a simple clone example also known as shallow cloning. This work only on objects that contains primitive variables. In the case of complex variables like other objects check the How to deep clone an object in Java tutorial.

Example

A simple model class. In order, the object to be available for cloning the class needs to extend the Cloneable interface.

package com.admfactory.clone;

public class User implements Cloneable {
    private String name;
    private String email;
    private int age;

    public String getName() {
	return name;
    }

    public void setName(String name) {
	this.name = name;
    }

    public String getEmail() {
	return email;
    }

    public void setEmail(String email) {
	this.email = email;
    }

    public int getAge() {
	return age;
    }

    public void setAge(int age) {
	this.age = age;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
	try {
	    return super.clone();
	} catch (CloneNotSupportedException e) {
	    System.out.println("CloneNotSupportedException thrown " + e);
	    throw new CloneNotSupportedException();
	}
    }

    @Override
    public String toString() {
	return "name: " + name + ", email: " + email + ", age: " + age;
    }
}

And here is the example of cloning.

package com.admfactory.clone;

public class CloneExample {
    public static void main(String[] args) throws CloneNotSupportedException {
	System.out.println("Object cloning example");
	System.out.println();

	/** defining one object */
	User user1 = new User();
	user1.setName("John Doe");
	user1.setEmail("john@example.com");
	user1.setAge(100);

	System.out.println("User 1: ");
	System.out.println(user1.toString());
	System.out.println();

	/**
	 * cloning the object - Notice the cast as the clone method from Cloneable
	 * returns Object
	 */
	User user2 = (User) user1.clone();
	System.out.println("User 2: ");
	System.out.println(user2.toString());
    }
}

Output

Object cloning example

User 1: 
name: John Doe, email: john@example.com, age: 100

User 2: 
name: John Doe, email: john@example.com, age: 100

You can notice that the output is the same.

 

 

 

References