Java Clone()


In this tutorial we will see about Java Clone and how to implement in our coding. Before jumping into coding lets discuss What is Java Clone and how its working.

What is Java Clone?
Clone is nothing but creating a copy of Object with the same state of cloning Object. For example if we clone a Object called "obj1" to "obj2" then new Object will be created with same state and value. There are Shallow copy and Deep copy which we will discuss in our next tutorial.

How its Working?
Suppose if we need to use clone for our class then we need to implement Cloneable interface in our class with clone() method, which will create a copy of super class and return's the Object. Below example will gives you how to use use clone() on user defined class and Collection Objects.

public class MyClass implements Cloneable {

 String name;
 String company;

 public MyClass(String name, String company) {
  System.out.println("Inside Constructor...."); = name; = company;

 public String getName() {

 public String getCompany() {

 public Object clone() {
  try {
   MyClass cloned = (MyClass) super.clone();
   return cloned;
  } catch (CloneNotSupportedException e) {
   return null;

public class JavaClone {
 public static void main(String[] args) {

  MyClass obj1 = new MyClass("Kamal", "ABC Limited.");

  System.out.println("\nName    : " + obj1.getName());
  System.out.println("Company : " + obj1.getCompany());

  // Cloning the Object
  MyClass obj2 = (MyClass) obj1.clone();

  System.out.println("\nName    : " + obj2.getName());
  System.out.println("Company : " + obj2.getCompany());

  ArrayList<String> arr1 = new ArrayList<String>();
  System.out.println("\nFirst ArrayList  : "+arr1);
  ArrayList<String> arr2 = (ArrayList<String>) arr1.clone();
  System.out.println("\nSecond ArrayList : "+arr2);


Inside Constructor....

Name    : Kamal
Company : ABC Limited.

Name    : Kamal
Company : ABC Limited.

First ArrayList  : [Java, J2EE]

Second ArrayList : [Java, J2EE]

1 comment:
Write comments