Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Program to demonstrate how to Clone an Object in Java

Program to demonstrate how to Clone an Object in Java

package com.hubberspot.example;

//1. class should implement Cloneable interface
public class Customer implements Cloneable {

   private int id;
   private String name;

   public String toString() {
 return "(id = " + id + ", name = " + name + ")";
   }
 
//2. class should override clone() method
//3. will throw CloneNotSupportedException exception if
// interface not implemented ... 
   @Override    
   protected Object clone() throws CloneNotSupportedException {
 return super.clone();
   }

   public static void main(String[] args) {
 Customer customer = new Customer();
 customer.id = 5;
 customer.name = "magicman";

 try {
       //4. calling clone() method to clone Customer
     Customer customerClone = (Customer) customer.clone();
     System.out.println("Cloned Customer before changes = " 
                           + customerClone);
   
     customerClone.id = 10;
     customerClone.name = "jonty";

     System.out.println("Cloned Customer after changes = " 
                           + customerClone);
     
            System.out.println("Original Customer = " + customer);
 } 
 catch (CloneNotSupportedException e) {
     e.printStackTrace();
 }
   } 
}






Output of the program :



 
© 2021 Learn Java by Examples Template by Hubberspot