Demonstrate the clone() method in Java

Java 8Object Oriented ProgrammingProgramming

An object can be cloned using the clone() method in Java. The class whose object is cloned should implement the interface java.lang.Cloneable otherwise the exception CloneNotSupportedException is thrown when clone() method is used.

A program that demonstrates the clone() method in Java is given as follows:

Example

 Live Demo

class CloneClass implements Cloneable {
   int x;
   char y;
   CloneClass cloneFunc() {
      try {
         return (CloneClass) super.clone();
      } catch (CloneNotSupportedException e) {
         System.out.println("Cloning cannot be done");
         return this;
      }
   }
}
public class Demo {
   public static void main(String args[]) {
      CloneClass obj1 = new CloneClass();
      CloneClass obj2;
      obj1.x = 8;
      obj1.y = 'A';
      obj2 = obj1.cloneFunc();
      System.out.println("For object obj1");
      System.out.println("obj1.x = " + obj1.x);
      System.out.println("obj1.y = " + obj1.y);
      System.out.println("\nFor object obj2");
      System.out.println("obj2.x = " + obj2.x);
      System.out.println("obj2.y = " + obj2.y);
   }  
}

Output

For object obj1
obj1.x = 8
obj1.y = A

For object obj2
obj2.x = 8
obj2.y = A
raja
Published on 15-Feb-2019 11:22:13
Advertisements